此 EntitySet 中已存在具有相同标识的实体。 - WCF RIA 服务
我有以下代码,我希望它会检查实体是否存在,如果不存在,则将其添加到集合中。然后,我在上下文中调用提交更改来保存更改。
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 组合进行测试:
Apple/Apple
iPad/iPad
iPod/iPod
第一次尝试从未运行 .Add 代码行。第二个成功了。第三个抛出错误此 EntitySet 中已存在具有相同标识的实体。
。
我读到这与身份和身份有关。种子,特别是当数据库中的种子为 0 时。我的不是(设置为1)。 EntitySet 本身包含约 1900 个项目。
我在这里缺少什么?
[编辑] 添加了 kwID 代码以显示关键字最终是条件中的 kwID。
该表的主键是ruleID。我认为错误消息中违反了这一点......但我不知道如何或为什么。
I have the following code that I would expect would check to see if an entity exists and, if not, add it to the collection. I then call submit changes on the context to save the changes.
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 });
}
I am testing this with 3 keywords/searchTerm combos:
Apple/Apple
iPad/iPad
iPod/iPod
The first attempt never runs the .Add line of code. The second does, successfully. The third throws the error An entity with the same identity already exists in this EntitySet.
.
I've read that this has something to do with the identity & seed, especially if your seed is 0 in the db. Mine isn't (set to 1). The EntitySet itself has ~1900 items in it.
What am I missing here?
[EDIT]
Added the kwID code to show that keyword is ultimately the kwID in the conditional.
The primaryKey of this table is ruleID. This is what I believe is being violated in the error message.... but I don't know how or why.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
恕我直言,错误的条件。
例子:
您的数据库中有:
在您的条件下输入值
this._context.Rules.Where(e => ; e.keywordID == 5 && e.searchTerm == "GooglePhone").FirstOrDefault()
返回 null,所以你尝试添加具有现有 KWid 的行。解决方案:更改&&条件为||
IMHO, wrong condition.
Example:
U've got in your DataBase:
And in your condition u put values
this._context.Rules.Where(e => e.keywordID == 5 && e.searchTerm == "GooglePhone").FirstOrDefault()
returns null and so u try to add a row with existing KWid.Solution: Change && condition to ||