簡體   English   中英

帶有字符串PK的EF InsertOrUpdate

[英]EF InsertOrUpdate with string PK

如果我有CurrencyId,我會做這樣的事情:

 public void InsertOrUpdate(Currency entity)
        {
            if (entity.CurrencyId == default(int))
            {
                // New entity
                this.dbset.Add(entity);
            }
            else
            {
                // Existing entity
                this.context.Entry(entity).State = EntityState.Modified;
            }
        }

但是我使用一個字符串CurrencyCode作為PK,並且希望能夠添加或編輯它。 所以我必須檢查CurrencyCode是否存在於數據庫中。 我該怎么做呢?

可以添加一個新的實體,但是如果我嘗試編輯:

 public void InsertOrUpdate(Currency entity)
        {
            if (GetByCurrency(entity.CurrencyCode) == null)
            {
                // New entity
                this.dbset.Add(entity);
            }
            else
            {
                // Existing entity
                this.context.Entry(entity).State = EntityState.Modified;
            }
        }

public Currency GetByCurrency(string currencyCode)
{
    return this.dbset.Find(currencyCode);
}

我越來越

具有相同鍵的對象已存在於ObjectStateManager中。 ObjectStateManager無法使用相同的鍵跟蹤多個對象。

this.context.Entry(entity).State = EntityState.Modified;

這是因為執行“查找”時,它將返回對象並將副本保留在緩存中。 然后,您要添加一個新副本,因此有兩個。

而是,您執行以下兩項操作之一。 您可以修改查找結果返回的副本,如果可以假設CurrencyCode == null表示該副本在數據庫中不存在,則只需添加或附加它。

因此,類似:

var currency = GetByCurrency(entity.CurrencyCode);

if (currency == null)
     this.dbset.Add(entity);
else
     currency.Something = entity.Something;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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