这些是我的实体:
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; }
}
第一次将值插入数据库时,一切正常,但如果我更改数据库中的任何值并尝试插入或更新记录,则会收到此错误:
操作失败:无法更改关系,因为
一个或多个外键属性不可为 null。当一个
对关系进行更改时,相关的外键属性是
设置为空值。如果外键不支持空值,
必须定义一个新的关系,外键属性必须是
分配另一个非空值,或者不相关的对象必须是
已删除。
这是我的插入代码:
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 https://stackoverflow.com/questions/5538974/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-pro。但我不明白我必须做什么。
我认为问题出在这个代码块上:
currency.CurrencyPrice = new List<CurrencyPrice>
{
new CurrencyPrice {Id = Guid.NewGuid().ToString(), EntryDate = DateTime.Now, Value = price,CurrencyId = currency.Id,Currency = currency}
};
在这里你创建一个新的CurrencyPrice
并将其分配给Currency
,从而孤立CurrencyPrice
分配给 this 的对象Currency
前。该对象现在仍在数据库中,但没有父对象。因此 EntityFramework 希望在此设置父级的 IDCurrencyPrice
to NULL
数据库阻止导致您引用的错误。我已经在这个问题上发布了更详细的解释这个答案 https://stackoverflow.com/questions/2554696/ef-4-removing-child-object-from-collection-does-not-delete-it-why/3710278#3710278.
为了防止这种情况发生,请删除旧的CurrencyPrice
在添加新数据库之前从您的数据库中获取。或者,因为看起来CurrencyPrice
对象总是依赖于它们Currency
家长,您可以考虑将其作为一种识别关系。我已经解释了如何使用 EntityFramework 4 Model First 创建它们,位于使用 EF4 实施识别关系 https://stackoverflow.com/questions/3710191/implementing-identifying-relationships-with-ef4。我还没有使用过 Code First,但方法应该是类似的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)