简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM