c# - Entity Framework 更新具有一对多关系的两个表

标签 c# entity-framework

我首先使用 EF 代码来控制我的数据。我有两个型号,ElectricitySiteElectricitySiteSplit .

ElectricitySite包含 List<ElectricitySiteSplits> ElectricitySiteSplits , 这是一对多的关系。

我正在尝试为将处理这两个表的存储库层编写我的更新方法,到目前为止我有:

public void UpdateElectricitySite(ElectricitySite updatedElectricitySite)
{
    var dbElectricitySite = GetElectricitySite(updatedElectricitySite.ElectricitySiteId);

    _context.ElectricitySites.Attach(updatedElectricitySite);
    _context.Entry(updatedElectricitySite).State = EntityState.Modified;

    _context.SaveChanges();
}

单击“保存”按钮时出现以下错误:

Attaching an entity of type 'MySolution.Repo.ElectricityModels.ElectricitySiteSplit' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

我认为这是因为我没有附上我的 ElectricitySiteSplit实体但是,如果我将其添加到我的 ElectricitySites 附件下方:

_context.ElectricitySiteSplits.Attach(updatedElectricitySite.SiteSplits);

我收到这个错误:

Severity Code Description Project File Line Suppression State Error CS1503 Argument 1: cannot convert from 'System.Collections.Generic.List' to 'UtilityBilling.Repo.ElectricityModels.ElectricitySiteSplit'

我如何处理 ElectricitySiteSplits updatedElectrcitiySite.SiteSplits 中包含的表更新作为列表。

仅供引用 - 我已经看过这里了:

Entity Framework 5 Updating a Record

https://msdn.microsoft.com/en-gb/data/jj592676.aspx

最佳答案

EF 不会自动处理这两个表。我必须指定添加/更新/删除了哪个项目。看看这个线程 Cleanly updating a hierarchy in Entity Framework

希望这对您有所帮助!

关于c# - Entity Framework 更新具有一对多关系的两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35199324/

相关文章:

c# - RuntimeHelpers.GetHashCode 是做什么的

visual-studio-2010 - 如何让实体数据模型与 SQL Server CE 4.0 一起使用?

c# - MVC3 + Entity Framework ,更新实体中的选择性字段

c# - 创建回文程序时出现逻辑错误

c# - 在哪里可以下载 Resharper 的命名标准/编码标准?

c# - ASP.NET SCORM 创作工具免费

c# - 如何处理 JSON 以从字段名称中删除句点?

c# - 使用 .Take() 方法对实体的 Linq 非常慢

entity-framework - Entity Framework 函数导入,无法加载返回实体类型的函数的关系

c# - 如何在不获取对象、更改对象和调用 SaveChanges 的情况下在 LINQ 中编写更新?