6

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();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
roadsunknown
  • 3,190
  • 6
  • 30
  • 36

1 Answers1

8

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,
             })
InteXX
  • 6,135
  • 6
  • 43
  • 80
Colin
  • 22,328
  • 17
  • 103
  • 197
  • Awesome. I didn't know the additional extension method. The natural key works great for updates. Unfortunately with [DatabaseGenerated(DatabaseGeneratedOption.Identity)] I'm assuming there is not a way to override the Guid / Id for new record? – roadsunknown Jul 18 '13 at 15:57
  • I doubt it. When I need the inserted ID during seeding I do this: var organisation = new Organisation { Name = "Demo" }; context.Organisations.AddOrUpdate(o => o.Name, organisation);SeedMembership(organisation.ID); – Colin Jul 18 '13 at 16:22