简体   繁体   中英

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:

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.

IMHO, wrong condition. Example: U've got in your DataBase:

  • KWid: 5, SearchTerm: iPod
  • KWid: 6, SearchTerm: iPad

And in your condition u put values

  • 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.

Solution: Change && condition to ||

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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