![](/img/trans.png)
[英]Entity Framework 5.0 code first one to one and one to many relationship
[英]Entity framework 6 code first one to one instead of one to many
我结束了一个首先使用EF6代码的项目。 我有2个类,其中设置了一对多的关系,在Fluent API中也设置了相同的关系。
当我在同一步骤中创建两个父级/子级时,一切都很好并保存了,但是当我先创建父级时,先保存它,然后我要添加一个子级,我得到了一个例外,指出这两个实体之间的关系为1 0..1,并且不保存。
有什么方法可以首先仅创建父级,然后向其添加子级?
模型类别:
public class Parent
{
public int ParentId {get; set;}
public virtual ICollection<Child> Children {get; set;}
}
public class Child
{
public int ChildId {get; set;}
public virtual Parent Parent {get; set;}
}
流利的API:
modelBuilder.Entity<Child>()
.HasRequired<Parent>(s => s.Parent)
.WithMany(s => s.Children)
.HasForeignKey(s => s.ParentId);
在数据库中,我看到了外键ParentId
。 如果我是对的,父母可以没有孩子而存在。 一切都用dbContext.SaveChanges()
保存
例外:
Exception thrown: 'System.Exception' in Project.dll
Additional information: Multiplicity constraint violated. The role 'Child_Parent_Target' of the relationship 'Project.DAL.Child_Parent' has multiplicity 1 or 0..1.
考虑给孩子一个ParentId属性
public class Child
{
public int ChildId {get; set;}
public int ParentId {get; set;}
public virtual Parent Parent {get; set;}
}
如果这样做,则遵循代码优先约定(单击以查看) 。 如果遵循约定,则Entity Framework会理解父级-子级是一对多关系:父级有零个或多个子级,而一个子级只有一个父级。
遵循约定的好处是,您不需要流利的API语句。 实体框架知道父级是必需的,父级有许多子级,并且父级的外键是ParentId
回到你的问题。 将ParentId添加到您的孩子之后,您可以添加没有孩子的父母,并在以后添加孩子。
添加ParentId之后,您可以添加一个父级并在以后添加子级
public class Parent
{
public int ParentId {get; set;}
public string Name {get; set;}
public virtual ICollection<Child> Children {get; set;}
}
public class Child
{
public int ChildId {get; set;}
public string Name {get; set;}
// By convention will become the foreign key to Parent:
public int ParentId {get; set;}
public virtual Parent Parent {get; set;}
}
public class MyDbContext : DbContext
{
public DbSet<Parent> Parents {get; set;}
public DbSet<Child> Children {get; set;}
}
public void Main()
{
using (var dbContext = new MyDbContext(...))
{
var addedParent = dbContext.Parents.Add(new Parent()
{
Name = "Phil Dunphy",
}
// if you do not want to add a child now, you can SaveChanges
dbContext.SaveChanges();
// now addedParent has a ParentId, you can add a child:
var addedChild = dbContext.Children.Add(new Child()
{
Name = "Luke Dunphy",
ParentId = addedParent.Id,
};
dbContext.SaveChanges();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.