gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:21:37 26 4
gpt4 key购买 nike

我首先使用 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/

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