C# EF Core-列不允许空值。插入失败
无法将值NULL插入到表的列“AttributeId”中 “表名”;列不允许空值。插入失败 我正在传递给EF Core以在数据库中插入新记录的对象 看起来像这样C# EF Core-列不允许空值。插入失败,c#,entity-framework,ef-core-2.1,C#,Entity Framework,Ef Core 2.1,无法将值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上下文。
public int Id { get; set; }
public string Value { get; set; }
public int AttributeId { get; set; }
public int CustomAttributeId { get; set; }
我得到一个对象的新实例,并将其传递给我的Db上下文。
但它抱怨AttributeId不能为null,这是有道理的。
但是属性的数据类型是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;
}
private只读AppContext\u db;
----------------
专用异步任务UpsertAttribute(lineAttribute属性)
{
_db.Entry(attr.State=attr.id数据类型必须可以为null,您可以将其设置为null,如下所示
public int?AttributeId{get;set;}表明我运行的迁移未正确运行。未对数据库上的列应用DefaultValue约束
谢谢大家
解决方案:
- 检查表的结构,确保fluent配置和数据库同步
您没有任何其他映射吗?INSERT语句是什么样子的?^查看执行INSERT语句的EF代码和INSERT语句会很有帮助itself@GertArnold我还认为有一个映射正在被应用,但没有。在我的开发机器上,它工作正常。我推了cod“我回家后会发布代码。刚离开办公室,@Gert问的是流畅的配置。例如,出现异常的一个可能原因可能是您使用了hasdaultvalue
,例如modelBuilder.Entity().Property(e=>e.AttributeId).HasDefaultValue(0)
或HasDefaultValueSql(…)
。其中任何一个都会导致EF在INSERT
命令中不包含AttributeId
和0
值。请看,这很可能会解决问题,但我想了解当int的默认值为零时,它的行为方式为何,这意味着它总是有一个值