这些是我的实体:
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; }
}
我第一次将值插入数据库时一切正常,但如果我更改数据库中的任何值并尝试插入或更新记录,我会收到此错误:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
这是我的插入代码:
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 并找到了 this .但我不明白我必须做什么。
最佳答案
我认为问题在于这个代码块:
currency.CurrencyPrice = new List<CurrencyPrice>
{
new CurrencyPrice {Id = Guid.NewGuid().ToString(), EntryDate = DateTime.Now, Value = price,CurrencyId = currency.Id,Currency = currency}
};
在这里您创建了一个新的 CurrencyPrice
并将其分配给一个 Currency
,从而孤立了分配给此 的
。该对象现在仍在数据库中,但没有父对象。因此,EntityFramework 想要将此 CurrencyPrice
对象之前的货币CurrencyPrice
上的父 ID 设置为 NULL
,数据库会阻止这导致您引用的错误。我在 this answer 中发布了对此问题的更详细解释。 .
为防止这种情况,请在添加新的之前从数据库中删除旧的 CurrencyPrice
。或者,由于 CurrencyPrice
对象似乎始终依赖于它们的 Currency
父对象,因此您可以考虑将其作为标识关系。我已经在 Implementing identifying relationships with EF4 解释了如何使用 EntityFramework 4 Model First 创建它们。 .我还没有使用过 Code First,但方法应该是相似的。
关于c# - 操作失败 : The relationship could not be changed because one or more of the foreign-key properties is non-nullable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17358293/