0

I am using EntityFramework version 4.4, code first and I have created my data model in a separate project (MyApp.DataModel). Because I am building a Silverlight application, I am using a WCF RIA services. The code required by the ria services is in a different project (MyApp.Services). This project has a reference to MyApp.DataModel.

An example of an data model:

   [Column("Remaining")]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public virtual decimal? Remaining
    {
       //
    }

When I build MyApp.Services I get an error

Duplicate 'System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedAttribute' attribute

Indeed, in the generated code there are two attributes

[System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Computed)]
[System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Computed)]

If I remove DatabaseGenerated, then on insert I get an error The column "Remaining" cannot be modified because it is either a computed column or is the result of a UNION operator.

Any idea why and how to solve this problem?

4

2 回答 2

0

据我了解这里的文档:http://msdn.microsoft.com/en-us/data/gg193958.aspxKey已经默认为DatabaseGeneratedOption.Identity,因此您不需要单独添加 DatabaseGenerated 。

摘自DatabaseGenerated下的部分:

密钥属性将成为数据库中的身份密钥。这与将 DatabaseGenerated 设置为 DatabaseGenerationOption.Identity 相同。如果您不希望它成为身份密钥,可以将值设置为 DatabaseGenerationOption.None。

老实说,我没有对此进行测试,但是您能否确认删除 [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 后,其他属性仍然保留在生成的代码中?

于 2012-06-22T12:42:32.690 回答
0

如果您将该属性标记为 DatabaseGeneratedOption.Identity,则 EF 会理解这是关键属性。实际上,如果您没有放置任何属性(Key 或 DatabaseGeneratedOption.Identity),EF 将假定这是 id,因为属性以“ID”结尾,并将在数据库中创建一个自动增量字段。DataAnnotations 在许多情况下是可选的(比如你的)。您也不需要将此属性标记为虚拟,因为它是原始类型。使用 virtual 只是为了关联其他类(延迟加载)。

于 2012-06-22T13:30:31.520 回答