简体   繁体   English

具有相同标识的实体已存在于此EntitySet中。 -WCF RIA服务

[英]An entity with the same identity already exists in this EntitySet. - WCF RIA Services

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: 我正在使用3个关键字/ searchTerm组合测试此功能:

Apple/Apple 苹果/苹果

iPad/iPad iPad / iPad

iPod/iPod iPod / iPod

The first attempt never runs the .Add line of code. 第一次尝试永远不会运行.Add代码行。 The second does, successfully. 第二个成功。 The third throws the error An entity with the same identity already exists in this EntitySet. 第三个引发错误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. 我读到这与身份和种子有关,特别是如果您的种子在数据库中为0时。 Mine isn't (set to 1). 我的不是(设置为1)。 The EntitySet itself has ~1900 items in it. EntitySet本身中包含约1900个项目。

What am I missing here? 我在这里想念什么?

[EDIT] Added the kwID code to show that keyword is ultimately the kwID in the conditional. [编辑]添加了kwID代码以显示关键字最终是条件关键字。

The primaryKey of this table is ruleID. 该表的primaryKey是ruleID。 This is what I believe is being violated in the error message.... but I don't know how or why. 我认为这是错误消息中所违反的...。但是我不知道如何或为什么。

IMHO, wrong condition. 恕我直言,条件错误。 Example: U've got in your DataBase: 示例:您已经进入数据库:

  • KWid: 5, SearchTerm: iPod KWid:5,搜索词:iPod
  • KWid: 6, SearchTerm: iPad KWid:6,搜索词:iPad

And in your condition u put values 在您的情况下,您会重视价值

  • KWid: 5, SearchTearm: GooglePhone KWid:5,SearchTearm:GooglePhone

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. this._context.Rules.Where(e => e.keywordID == 5 && e.searchTerm == "GooglePhone").FirstOrDefault()返回null,因此您尝试添加具有现有KWid的行。

Solution: Change && condition to || 解决方案:将&&条件更改为||

if ( null == this._context.Rules.Where(e => e.keywordID == kwID || e.searchTerm == item.SearchTerm).FirstOrDefault())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM