简体   繁体   English

实体框架主键初始化

[英]Entity Framework Primary Key Initialization

I using EF 6.0 model first. 我首先使用EF 6.0模型。 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. 当我使用new运算符创建Entity时,主键始终设置为0。在此过程的后面,我无法执行上下文保存。 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. 在SaveChanges之前您无法获得ID。 Because primary key is set by database engine. 因为主键是由数据库引擎设置的。 All you can do you is to refer to realeted object not to id. 您所能做的就是不要将引用的对象引用为id。 Then EF do the save in proper way. 然后,EF以适当的方式进行保存。 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. 然后,您可以使用引用轻松保存,并且在SaveChanges之后将填写ID。

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. 如果必须在客户端上设置主键,则可能要删除DatabaseGeneratedOption .Identity为None,然后从int切换为guid,然后将值手动设置为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. 从性能的角度来看,我实际上并不是这种方法的支持者,您希望主键是最小的可行数据类型,但是如果您需要按通常的方式在数据库外部生成主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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