[英]Unexpected “An entity with the same identity already exists in this EntitySet”?
[英]An entity with the same identity already exists in this EntitySet. - WCF RIA Services
我有以下代码,希望可以检查一下是否存在实体,如果不存在,请将其添加到集合中。 然后,我在上下文上调用提交更改以保存更改。
int kwID = (int)(from d in this._keywordSource.Source where d.keyword.ToLower() == searchText.ToLower() select d.keywordID).FirstOrDefault();
if ( null == this._context.Rules.Where(e => e.keywordID == kwID && e.searchTerm == item.SearchTerm).FirstOrDefault())
{
this._context.Rules.Add(new Rule() { keywordID = kwID, searchTerm = item.SearchTerm, processed = false });
}
我正在使用3个关键字/ searchTerm组合测试此功能:
苹果/苹果
iPad / iPad
iPod / iPod
第一次尝试永远不会运行.Add代码行。 第二个成功。 第三个引发错误An entity with the same identity already exists in this EntitySet.
。
我读到这与身份和种子有关,特别是如果您的种子在数据库中为0时。 我的不是(设置为1)。 EntitySet本身中包含约1900个项目。
我在这里想念什么?
[编辑]添加了kwID代码以显示关键字最终是条件关键字。
该表的primaryKey是ruleID。 我认为这是错误消息中所违反的...。但是我不知道如何或为什么。
恕我直言,条件错误。 示例:您已经进入数据库:
在您的情况下,您会重视价值
this._context.Rules.Where(e => e.keywordID == 5 && e.searchTerm == "GooglePhone").FirstOrDefault()
返回null,因此您尝试添加具有现有KWid的行。
解决方案:将&&条件更改为||
if ( null == this._context.Rules.Where(e => e.keywordID == kwID || e.searchTerm == item.SearchTerm).FirstOrDefault())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.