EF Core - 列不允许空值。插入失败

EF Core - column does not allow nulls. INSERT fails

Cannot insert the value NULL into column 'AttributeId', table 'TableName'; column does not allow nulls. INSERT fails.

我传递给 EF Core 以在数据库中插入新记录的对象 看起来像这样

public int Id { get; set; }
public string Value { get; set; }
public int AttributeId { get; set; }
public int CustomAttributeId { get; set; }

我获得了该对象的一个​​新实例并将其传递到我的 Db 上下文。 但它抱怨 AttributeId 不能为空,这是有道理的。 但是属性的数据类型是Int。我不太确定为什么 EF Core 将该值解释为 null。我什至硬编码了一个零,但它仍然抱怨。

有没有人遇到过类似的问题?在 UpsertAttribute()

中抛出错误

更新

核心层

Db.LineAttribute lineAttribute = new Db.LineAttribute()
{
    Value = attribute.Value ?? "",
    CustomAttributeId = attribute.Id,
};

if (attribute.Values.Count > 0 && String.IsNullOrEmpty(attribute.Value))
{
    if (attribute.Values.Where(x => x.IsDefault == true && x.Id == -1).Count() == 1)
    {
        // Set default value
        lineAttribute.Value = attribute
           .Values
           .FirstOrDefault(x => x.Id == -1)
           .InternalValue;
    }
    else
    {
        // Set user selected default value
        lineAttribute.Value = attribute
            .Values
            .FirstOrDefault(x => x.IsDefault = true)
            .InternalValue;
    }
}

lineAttribute = await _dataLayer.UpsertAttribute(lineAttribute);

数据层

private readonly AppContext _db;

----------------

private async Task<lineAttribute> UpsertAttribute(lineAttribute attr)
{
    _db.Entry(attr).State = attr.id <= 0 ? EntityState.Added : EntityState.Modified;
    await _db.SaveChanges();

    return attr;
}

数据类型必须是可为空的,您可以像下面那样使其为空

public提示?属性 ID { 获取;放; }

事实证明,我 运行 的迁移没有 运行 正确。 DefaultValue 约束未应用于数据库中的列。

谢谢大家

解法:

  • 检查您的 table 结构并确保 Fluent 配置和数据库同步。

我遇到了这个问题,我的 Entity 模型和 IEntityTypeConfiguration 实现完全同步。

问题来了,我完全忘记了我已经在数据库上有一些条目,其中有一列以前是 int?NULL,并将模型精确更新为 decimal ,所以 EF 真的不知道如何将 NULL 翻译成 default(decimal),而实际上它甚至不应该是 NULL.

只需确保您的实际条目可以转换为从现在开始应用的类型