实体框架7级联插入 [英] Entity Framework 7 cascading inserts

查看:76
本文介绍了实体框架7级联插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我们在应用程序中使用ASP.Net 5,因此我们刚刚完成了从EF6到EF7的合并。该项目才刚刚开始,因此我们不会遇到发布依赖Beta库的代码的问题。

We have just done a merge to EF7 from EF6, since we use ASP.Net 5 in our application. The project is just started, so we won't run into issues with releasing code dependent on beta libraries.

我们遇到了级联插入的问题。通过级联插入,我的意思是插入/更新父级子实体集合。

We have run into an issue with cascading inserts. By cascading inserts I mean that a collection of child entities is inserted / updated with the parent. It seems to be dependent on the order of operations in a surprising way.

给出以下定义:

public class ParentEntity
{
    public int Id { get; set; }
    public ICollection<ChildEntity> Children { get; set; }
}

public class ChildEntity
{
    public int Id { get;set; }

    public ParentEntity Parent { get; set; }
}

以下代码有效(ChildTable填充了3个值):

the following code works (ChildTable is populated with 3 values):

var parent = new ParentEntity();            

parentSet.Add(parent);

parent.Children = new List<ChildEntity>();

for (int i = 0; i < 3; i++)
{
    var child= new ChildEntity { Parent = parent };
    parent.Children.Add(child);
}

_uow.SaveChanges();

但以下内容并非如此(ChildTable保持为空):

But the following does not (ChildTable remains empty):

var parent = new ParentEntity();                

// Moved parentSet.Add()

parent.Children = new List<ChildEntity>();

for (int i = 0; i < 3; i++)
{
    var child= new ChildEntity { Parent = parent };
    parent.Children.Add(child);
}

parentSet.Add(parent);

_uow.SaveChanges();

要完成以下工作,我必须执行以下操作:

To make the below work, I have to do the following:

var parent = new ParentEntity();                

parent.Children = new List<ChildEntity>();

for (int i = 0; i < 3; i++)
{
    var child= new ChildEntity { Parent = parent };
    parent.Children.Add(child);
    childSet.Add(child); // Added childSet.Add()
}

parentSet.Add(parent);

_uow.SaveChanges();

有人可以解释为什么会有这种区别吗?在EF6中,这按我的预期工作。我想知道EF7是否还不支持自动跟踪的子实体,但是显然,如果移动Set.Add调用,您可以使其正常工作。让我感到惊讶的是,将Set.Add调用移到填充子集合之前才起作用。

Can someone explain why there is such a difference? In EF6, this works as I expect it to. I would understand if there wasn't support yet in EF7 for automatically tracked child entities, but obviously you can make it work if you move the Set.Add call around. It is even more surprising to me that moving the Set.Add call to ahead of when the child collection is populated is what works.

任何想法/解释吗?

我们使用EF7 beta 7。

We use EF7 beta 7.

推荐答案

我们正在积极努力使这表现出预期。有关我们的最新想法,请参见我们的 2015年8月27日设计会议笔记

We're actively working to make this behave as expected. For our latest thoughts, please see our August 27, 2015 Design Meeting Notes.

这篇关于实体框架7级联插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆