gpt4 book ai didi

c# - 无法使用已使用的键(LINQ)添加实体

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

当我运行以下代码时,出现此错误Cannot add an entity with a key that is already in use.

表格:


我想念什么?

    private void CopyAllPageObjects(int fromPageID, int toPageID)
{
CMSDataContext _db = new CMSDataContext();

// Copy page objects
var originalPageObjects = (from x in _db.CMSPageObjects
where x.PageID == fromPageID
select x);

List<CMSPageObject> newPageObjects = new List<CMSPageObject>();
foreach (CMSPageObject po in originalPageObjects)
{
CMSPageObject newPageObject = new CMSPageObject();
newPageObject.PageID = toPageID;
newPageObject.CMSObjectID = po.CMSObjectID;
newPageObject.Name = po.Name;
newPageObject.Sorting = po.Sorting;
newPageObjects.Add(newPageObject);

// Copy page object attribute values
var originalPoavs = (from x in _db.CMSPageObjectAttributeValues
where x.CMSPageObjectID == po.ID
select x);

List<CMSPageObjectAttributeValue> newPoavs = new List<CMSPageObjectAttributeValue>();
foreach (CMSPageObjectAttributeValue poav in originalPoavs)
{
CMSPageObjectAttributeValue newPoav = new CMSPageObjectAttributeValue();
newPoav.CMSAttributeID = poav.CMSAttributeID;
newPoav.CMSPageObjectID = newPageObject.ID;
newPoav.LCID = poav.LCID;
newPoav.Value = poav.Value;
newPoavs.Add(newPoav);
}
_db.CMSPageObjectAttributeValues.InsertAllOnSubmit(newPoavs);
}

_db.CMSPageObjects.InsertAllOnSubmit(newPageObjects);
_db.SubmitChanges();
}

最佳答案

似乎您要添加一个对象,而存在另一个具有相同主键的对象。是PageID还是CMSObjectID主键?还是CMSAttributeID

您可能还希望共享有关数据表外观的更多数据。

更新:添加数据库结构后,我将更仔细地浏览以下行:

newPoav.CMSPageObjectID = newPageObject.ID;


newPageObject.ID可能目前未知,因为您尚未将对象添加到数据库中(我怀疑 是身份)。我认为您可以使用:

newPoav.CMSPageObject = newPageObject

关于c# - 无法使用已使用的键(LINQ)添加实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9681381/

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