Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've seen many posts and answers regarding how to mark a field as the identity column. Many of them are outdated and are targeting older versions of Entity Framework.

Some resources tell me to use an attribute on the field:

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

Other resources tell me to add this code to OnModelCreating method:

modelBuilder.Entity<User>().Property(u => u.ID).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);

Which one should I use? First, second, both, doesn't matter, or something else?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
518 views
Welcome To Ask or Share your Answers For Others

1 Answer

As long as the type of the primary key property is numeric or GUID, Code First will, by convention, automatically configure the key as an identity column.

That means you don't need to have any of the configuration you put in your code to explicity set the property as an identity column because Code First already use covention for that. The data annotation attribute or fluent API configurations you set are useless.

You use those configurations on numeric or GUID type primary key only if you want to disable the identity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...