这些是我的实体:
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; }
}
Run Code Online (Sandbox Code Playgroud)
我第一次将值插入数据库时一切正常,但如果我更改数据库中的任何值并尝试插入或更新记录,我会收到此错误:
操作失败:无法更改关系,因为一个或多个外键属性不可为空.当对关系进行更改时,相关的外键属性将设置为空值.如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象.
这是我的插入代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
我搜索了StackOverflow并找到了这个.但我不明白我该做什么.
Chr*_*ris 10
我认为问题出在这个代码块中:
currency.CurrencyPrice = new List<CurrencyPrice>
{
new CurrencyPrice {Id = Guid.NewGuid().ToString(), EntryDate = DateTime.Now, Value = price,CurrencyId = currency.Id,Currency = currency}
};
Run Code Online (Sandbox Code Playgroud)
在这里,您创建一个新的CurrencyPrice并将其分配给a Currency,从而使之前分配给它的CurrencyPrice对象孤立Currency.此对象现在仍在数据库中,但没有父对象.因此,EntityFramework希望在此数据库上设置父ID,CurrencyPrice以NULL防止导致您引用的错误.我在这个答案中已经对这个问题发布了更详细的解释.
要防止这种情况,CurrencyPrice请在添加新数据库之前从数据库中删除旧数据库.或者,由于CurrencyPrice对象似乎总是依赖于Currency父对象,因此您可以考虑将其作为识别关系.我已经解释了如何使用EntityFramework 4 Model First在实现与EF4的识别关系时创建它们.我还没有使用Code First,但方法应该类似.