user1830498
user1830498

Reputation: 13

Entity Framework Primary Key Initialization

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

Upvotes: 0

Views: 1517

Answers (2)

py3r3str
py3r3str

Reputation: 1879

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();

Upvotes: 1

Miniver Cheevy
Miniver Cheevy

Reputation: 1677

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.

Upvotes: 0

Related Questions