【问题标题】:EF Core - column does not allow nulls. INSERT failsEF Core - 列不允许空值。插入失败
【发布时间】:2019-02-02 14:17:34
【问题描述】:

无法将值 NULL 插入列“AttributeId”,表 '表名';列不允许空值。插入失败。

我传递给 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;
}

【问题讨论】:

  • 您没有其他映射吗? INSERT 语句是什么样的?
  • ^ 查看完成插入语句的 EF 代码和插入语句本身会很有帮助
  • @GertArnold 我还认为有一个正在应用的映射但没有。在我的开发机器上,它可以正常工作。我早些时候将代码推送到暂存,它开始抱怨。
  • @devNull 我回家后会发布代码。刚离开办公室。
  • @Gert 要求的是流畅的配置。例如,异常的一个可能原因可能是您使用了HasDefaultValue,例如类似modelBuilder.Entity&lt;LineAttribute&gt;().Property(e =&gt; e.AttributeId).HasDefaultValue(0)。或HasDefaultValueSql(…)。其中任何一个都将导致 EF 在 INSERT 命令中不包括 AttributeId0 值。见Default Values

标签: c# entity-framework ef-core-2.1


【解决方案1】:

原来我运行的迁移没有正常运行。 DefaultValue 约束未应用于数据库上的列。

谢谢大家。

解决方案:

  • 检查表结构,确保流畅配置和数据库同步。

【讨论】:

    【解决方案2】:

    数据类型必须可以为空,你可以像下面这样设置为空

    公共整数?属性 ID { 获取;放; }

    【讨论】:

    • 这很可能会解决问题,但我想了解为什么当 int 的默认值为零时它的行为方式是这样的,这意味着它总是有一个值
    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 2023-03-22
      • 2017-12-07
      相关资源
      最近更新 更多