这些是我的实体:
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 值。如果外键不支持 null 值,则必须定义新关系,将外键属性分配为另一个非 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上搜索并找到了这个。但是我不理解我需要做什么。