Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

c# - How to Handle Primary Key in Entity Framework 5 Code First

In my EF5 code-first models, creation of new records works better if the database sets the primary key. I am using a Guid for primary key and if DatabaseGeneratedOption.Identity is set, SQL Server will always create the uniqueidentifier.

However, this causes issues when I am trying to initially seed the database. If I set the Guid in my seed method, SQL Server overrides it. If I don't set the Guid, I get a new record every time. What is a recommended solution to seed the database using pre-set Guids and keep DatabaseGeneratedOption.Identity set for my normal operations?

Example class model:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public RecordName { get; set; }
public DateTime? Created { get; set; }
public DateTime? Updated { get; set; }

Example seed method:

var record = new Record()
            {
                Id = new Guid("3B80725E-9550-4933-807F-C2FAA0942225"),
                RecordName = "New Record",
                Created = DateTime.UtcNow,
                Updated = DateTime.UtcNow,
             };
context.Record.AddOrUpdate(record);
context.SaveChanges();
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

AddOrUpdate has an overload that allows you to specify the key

From MSDN

So you need to supply the method with the natural key:

context.Record.AddOrUpdate(c => c.RecordName, new Record()
            {
                RecordName = "New Record",
                Created = DateTime.UtcNow,
                Updated = DateTime.UtcNow,
             })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...