在Entity Framework Core中更新父实体时添加或更新子实体

时间:2019-12-21 22:08:44

标签: c# entity-framework entity-framework-core entity-framework-core-2.2 entity-framework-core-3.1

在一个新项目中,我们使用Entity Framework Core而不是EntityFramework 6.2.0。效果很好,但在更新父母子女并插入新子女时会引起问题。

示例:

当前型号:

public class Profile
{

    public Profile()
    {
        Interests = new List<Interest>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public ICollection<Interest> Interests { get; set; }

}

public class Interest
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Name { get; set; }

}

在Entity Framework中添加或更新子代的代码,在EntityFramework 6.2.0中工作正常

//Interests
//Delete children
foreach (var existingChild in dbProfile.Interests.ToList())
{
    if (!profile.Interests.Any(c => c.Name == existingChild.Name))
        db.Interests.Remove(existingChild);
}

//Update and Insert children
foreach (var childModel in profile.Interests)
{
    var existingChild = dbProfile.Interests
        .Where(c => c.Name == childModel.Name)
        .SingleOrDefault();

    if (existingChild != null)
    {
        // Update child
        childModel.Id = existingChild.Id;
        db.Entry(existingChild).CurrentValues.SetValues(childModel);
    }
    else
    {
        // Insert child
        var newChild = new Interest
        {
            Name = childModel.Name,
        };
        dbProfile.Interests.Add(newChild);
    }
}

代码基于以下答案:

https://stackoverflow.com/a/27177623/3850405

使用Microsoft.EntityFrameworkCore 2.2.6时会发生这种情况:

新的兴趣添加到Id 0中。

enter image description here

但是,如果发生更新并且运行了以下代码:

db.Entry(existingChild).CurrentValues.SetValues(childModel);

每个带有Id 0的新对象的Id都设置为-2147482197。即使没有为父对象设置任何内容,也只有一个子对象,否则会发生这种情况。为什么会这样?有什么方法可以代替EF Core中的上述方法?

enter image description here

我可以通过删除db.Entry(existingChild).CurrentValues.SetValues(childModel);并将其替换为childModel.Name = existingChild.Name;来解决此问题。但是,如果该对象具有20个或更多属性,则我不想手动将它们一一对应。

enter image description here

1 个答案:

答案 0 :(得分:1)

将以下NuGet从2.2.6更新为3.1.0,然后一切开始正常运行:

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools