ASP.NET vNext DataAnnotations DatabaseGenerated无法正常工作

时间:2015-04-18 19:45:30

标签: c# asp.net asp.net-mvc data-annotations

我尝试在ASP.NET 5中定义这样的模型ID变量:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

为了支持数据注释,我在我的project.json文件中添加了包System.ComponentModel.DataAnnotations,如下所示:

"System.ComponentModel.Annotations": "4.0.10-beta-22811"

在模型cs文件中,我添加了using System.ComponentModel.DataAnnotations.Schema;

虽然我收到以下错误:

  

错误CS0433类型' DatabaseGeneratedAttribute'存在于&System; .ComponentModel.Annotations,Version = 4.0.10.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a'和' System.ComponentModel.DataAnnotations,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35'

而且我不知道应该如何解决这个问题。我尝试将名称空间System.ComponentModel.Annotations包含在内,而不是System.ComponentModel.DataAnnotations,但似乎它不存在,因为我收到此错误:

  

错误CS0234类型或命名空间名称'注释'名称空间中不存在System.ComponentModel' (你错过了一个程序集引用吗?)

如果该命名空间不存在,我不明白我是如何得到之前的错误,它告诉我DatabaseGeneratedAttribute存在于两个地方。

我真的很感激能得到的所有帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用KeyAttribute。那应该为你做自动生成。

[Key]
public int Id { get; set; }

此属性在System.ComponentModel.DataAnnotations命名空间

中可用

但是,如果要继续使用DatabaseGeneratedAttribute。这个错误非常自我解释。它告诉您它在两个命名空间中都可用

System.ComponentModel.DataAnnotations     
System.ComponentModel.DataAnnotations.Schema

您需要明确说明您需要使用的名称空间(例如

[System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]

您始终可以使用别名来保持命名空间的简洁和甜蜜。

答案 1 :(得分:1)

请检查您的项目是否没有引用这两个版本的System.ComponentModel.DataAnnotations.dll程序集。

默认情况下,旧版本(4.0.0.0)可以包含在您的项目中,并且在使用新版本(4.0.10.0)安装软件包后不会将其删除。