gpt4 book ai didi

c# - Entity Framework 7 中的子元素插入

转载 作者:行者123 更新时间:2023-11-30 23:29:12 24 4
gpt4 key购买 nike

我将 ASP.NET 5 与 Entity Framework 7 结合使用。我有这个模型:

public class ParentModel
{
public Guid Id { get; set; }
public virtual ChildModel Children { get; set; }
}

public class ChildModel
{
public Guid Id { get; set; }

public virtual AnotherChildModel AnotherChild { get; set; }
}

public class AnotherChildModel
{
public Guid Id { get; set; }

public string Text { get; set; }
}

当我尝试将 ParentModel 添加到数据库时,它不会自动将 ChildModel 和 AnotherChildModel 添加到数据库,而 ParentModel 在代码中完全正确,例如:

var parent = new ParentModel() { Children = new ChildModel() { AnotherChild = new AnotherChildModel() { Text = "sometext" }}};

所以,简单的 parentSet.Add(parent) 不起作用,除了手动添加集合中的所有模型之外,还有其他方法吗?

编辑:

我有异常:

DbUpdateException: An error occurred while updating the entries. See the inner exception for details. 
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ParentModel_ChildModel_ChildrenId". The conflict occurred in database "aspnet5-WebApplication1-922849d0-b7da-4169-8150-9a2d05240a47", table "dbo.ChildModel", column 'Id'. The statement has been terminated.

最佳答案

在 EF7 的当前 RC1 版本中,Add() 仅在集合(即真正的)中递归添加粘附对象,而不是 < em>引用实体,就像 EF6 所做的那样。

因此,如果您有以下模型(这与您选择的名称更一致)...

public class ParentModel
{
public Guid Id { get; set; }
public virtual ICollection<ChildModel> Children { get; set; }
}

...子项也可以通过单个语句parentSet.Add(parent) 添加。

我不知道这是否是预期的行为。事实证明,RC 会带来“发布候选”不应该出现的问题。但也许这是一个受 OO 启发的设计决定, parent 封装了他们的 child ,而不是相反。

关于c# - Entity Framework 7 中的子元素插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35608770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com