c# - 操作失败 : The relationship could not be changed because one or more of the foreign-key properties is non-nullable

标签 c# entity-framework

这些是我的实体:

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,从而孤立了分配给此 CurrencyPrice 对象之前的货币。该对象现在仍在数据库中,但没有父对象。因此,EntityFramework 想要将此 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/

相关文章:

c# - 分段长度前缀导致从缓冲区读取的下一个数据使用不正确的消息长度

c# - 如果非零,则继续四舍五入到指定数字

c# - EntityFramework 修改数据库而不是重新创建

c# - 并非所有代码路径都返回值: Unity

c# - Entity Framework ISNULL 在 Where 条件

c# - 首先使用实体​​框架代码获取外键值

entity-framework - Entity Framework 4.1代码优先自引用一对多和多对多关联

entity-framework - 代码优先 EF6 SqlServerMigrationSqlGenerator 中的自定义逻辑不起作用

c# - 如何在没有 Shift、Control 或 Alt 要求的情况下将键盘快捷键分配给 asp.net 按钮?

c# - 在 Entity Framework 中创建递归实体的正确方法是什么?