0

I using EF 6.0 model first. I have an Entity with a primary key. When I create the Entity using the new operator the primary key is always set to 0. I cannot perform a context save until later in the process. In other parts of the code it is necessary to reference the primary key. As a workaround I am setting the primary key to a unique value manually. Is there anyway I can get the system to generate the primary key automatically?

Thanks in advance, Terry

2
  • If the database is generating the key then you'd get a key by persisting the record to the database. Commented Oct 2, 2014 at 18:24
  • This covers how EF deals with store generated primary keys: stackoverflow.com/questions/5333417/… Commented Oct 2, 2014 at 18:27

2 Answers 2

1

You can't get Id before SaveChanges. Because primary key is set by database engine. All you can do you is to refer to realeted object not to id. Then EF do the save in proper way. Your model can look:

class Parent { public int Id { get; set; } public List<Child> Children { get; set; } } class Child { public int Id { get; set; } public int ParentId { get; set; } public Parent Parent { get; set; } } 

Then you can easy save using references and Ids will be fill after SaveChanges.

var parent = new Parent() parent.Childs = new List<Child>() var child1 = new Child(); var child2 = new Child(); parent.Childs.Add(child1); parent.Childs.Add(child2); dbContex.Parents.Add(parent); dbContex.SaveChanges(); 
Sign up to request clarification or add additional context in comments.

Comments

0

If you have to set the primary key on the client side you might want to remove DatabaseGeneratedOption.Identity to None, and switch from an int to a guid and manually set the value to Guid.NewGuid. I'm not actually a fan of this approach, from a performance standpoint you want your primary key to be the smallest viable datatype, but if you need to generate your primary key outside of the database that is the way it's typically done.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.