简体   繁体   中英

ASP.NET vNext DataAnnotations DatabaseGenerated not working

I'm trying define a model ID variable like this in ASP.NET 5:

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

To support data annotations I've added the package System.ComponentModel.DataAnnotations in my project.json file like this:

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

And in the model cs file I've added using System.ComponentModel.DataAnnotations.Schema;

Though I get the following error:

Error CS0433 The type 'DatabaseGeneratedAttribute' exists in both 'System.ComponentModel.Annotations, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' and 'System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

And I don't know how I should fix this really. I've tried to include the namespace System.ComponentModel.Annotations instead of System.ComponentModel.DataAnnotations but it seems like it doesn't exist as I get this error then:

Error CS0234 The type or namespace name 'Annotations' does not exist in the namespace 'System.ComponentModel' (are you missing an assembly reference?)

And if that namespace does not exist I don't understand how I can get the previous error which tells me that DatabaseGeneratedAttribute exists in two places.

I would really appreciate all help I can get with this.

You can just use the KeyAttribute. That should do the auto generation for you.

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

This attribute is available in the System.ComponentModel.DataAnnotations namespace

However, if you want to continue using the DatabaseGeneratedAttribute. The error is pretty self explanatory. It tells you that it is available in both namespaces

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

You will need to explicity state the namespace you need to use Eg

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

You can always use an alias to keep the namespace short and sweet.

Please check that your project does not have reference to both version of System.ComponentModel.DataAnnotations.dll assembly.

Old version (4.0.0.0) can be included to your project by default, and do not be removed after you install package with new version (4.0.10.0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM