簡體   English   中英

具有相同標識的實體已存在於此EntitySet中。 -WCF RIA服務

[英]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。 我認為這是錯誤消息中所違反的...。但是我不知道如何或為什么。

恕我直言,條件錯誤。 示例:您已經進入數據庫:

  • KWid:5,搜索詞:iPod
  • KWid:6,搜索詞:iPad

在您的情況下,您會重視價值

  • KWid:5,SearchTearm:GooglePhone

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM