These are my entities:
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 first time I insert a value into the DB everything is OK but if I change any value in the DB and try to insert or update the record I get this error:
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.
This is my insert code:
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();
}
I searched StackOverflow and found this. But I don't understand what I have to do.