use*_*491 26 entity-framework code-first ef-code-first
我有以下型号.
class Parent
{
int ParentId (identity column) { get; set; }
string ParentName { get; set; }
virtual ICollection<Child> Children { get; set; }
}
class Child
{
int ChildId (identity column) { get; set; }
string ChildName { get; set; }
int ParentID { get ; set; } //foreign key to Parent(ParentID)
}
Run Code Online (Sandbox Code Playgroud)
如何在单个事务中向父母和子女插入几行?基本上我想获得在父级上生成的标识(比如我在父级中插入一行)并插入具有该值的子行?如何使用Code First实现这一目标?
Ser*_*eit 41
您不应该担心Parent为了插入Child行而获得Id的值.这应该足够了:
var parent = new Parent
{
// fill other properties
Children = new List<Child>()
}
parent.Children.add(new Child { /*fill values */);
dbContext.Parents.Add(parent); // whatever your context is named
dbContext.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
对于记录,ID将在调用后分配SaveChanges(),因此如果在插入实体之前确实需要ID,则Child可以始终调用SaveChanges()两次.
同样,这不应该是必要的.
顺便说一句,我建议将Foreign Key属性Child设置Parent为导航属性,因此Child该类看起来像:
class Child
{
public int ChildId { get; set; } // identity column
public string ChildName { get; set; }
public virtual Parent Parent { get ; set; } //foreign key to Parent
}
Run Code Online (Sandbox Code Playgroud)
这样你就可以直接访问Child的父级而无需自己从数据库中显式地检索它(它将被延迟加载).