簡體   English   中英

操作失敗:無法更改關系,因為一個或多個外鍵屬性不可為空

[英]The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable

這些是我的實體:

public class Currency : Exchange
{
     public List<CurrencyPrice> CurrencyPrice { get; set; }
}

public class CurrencyPrice : Price
{
    public int CurrencyId { get; set; }
    [ForeignKey("CurrencyId")]
    public Currency Currency { get; set; }
}

我第一次將值插入數據庫時​​一切正常,但如果我更改數據庫中的任何值並嘗試插入或更新記錄,我會收到此錯誤:

操作失敗:無法更改關系,因為一個或多個外鍵屬性不可為空。 當對關系進行更改時,相關的外鍵屬性將設置為空值。 如果外鍵不支持空值,則必須定義新關系,必須為外鍵屬性分配另一個非空值,或者必須刪除不相關的對象。

這是我的插入代碼:

var currency =
    UnitOfWork.Exchange.Get(x => x is Currency && x.ExchangeType.Id == exchangeTypeId) as Currency;
if (currency != null)
{
    CurrencyPrice lastPriceValue = UnitOfWork.CurrencyPrice.Last(x => x.CurrencyId == currency.Id);
    if (lastPriceValue == null || lastPriceValue.Value != price)
    {
        currency.CurrencyPrice = new List<CurrencyPrice>
            {
                new CurrencyPrice {Id = Guid.NewGuid().ToString(), EntryDate = DateTime.Now, Value = price,CurrencyId = currency.Id,Currency = currency}
            };
    }
    else
    {
        lastPriceValue.EntryDate = DateTime.Now;
    }

    UnitOfWork.Commit();
}

我搜索了StackOverflow並找到了這個 但我不明白我該做什么。

我認為問題出在這個代碼塊中:

currency.CurrencyPrice = new List<CurrencyPrice>
{
    new CurrencyPrice {Id = Guid.NewGuid().ToString(), EntryDate = DateTime.Now, Value = price,CurrencyId = currency.Id,Currency = currency}
};

在這里,您可以創建一個新的CurrencyPrice並將其分配給Currency ,從而孤立分配給此CurrencyCurrencyPrice對象。 此對象現在仍在數據庫中,但沒有父對象。 因此,EntityFramework希望將此CurrencyPrice上的父ID設置為NULL ,數據庫會阻止該ID導致您引用的錯誤。 我在這個答案中已經對這個問題發布了更詳細的解釋。

要防止這種情況,請在添加新的CurrencyPrice之前從數據庫中刪除舊的CurrencyPrice 或者,由於看起來CurrencyPrice對象總是依賴於其Currency父級,因此您可以考慮將其設置為標識關系。 我已經解釋了如何使用EntityFramework 4 Model First在實現與EF4的識別關系時創建它們。 我還沒有使用Code First,但方法應該類似。

保存上下文更改時出現相同錯誤,並且未對實體或關系進行任何更改。

錯誤是因為某些實體具有ovveridden的GetHashCode()方法

暫無
暫無

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

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