【发布时间】:2015-11-03 02:53:54
【问题描述】:
这个问题已经在 SO 上被问过很多次,但其他答案都没有帮助。我正在插入一个表(SQL Server 2014,EF 6),我收到错误Cannot insert the value NULL into column 'Id' ... column does not allow nulls. Id 列在我的数据库中设置为主键并且是一个标识列,我已经三重检查。我可以在不使用 SSMS 中的 T-SQL 指定 Id 的情况下插入,但 EF 失败。它传递了0 的值;我不明白为什么它不被接受。我不使用任何数据注释,我只使用流畅的映射。
This answer 和 this answer 都使用数据注释,不应用于此项目。这在没有注释的情况下可以正常工作;我不知道是什么改变导致了这个。
类:
namespace Nop.Core.Domain.Common
{
public partial class GenericAttribute : BaseEntity
{
// Id is inherited from BaseEntity
public virtual int EntityId { get; set; }
public virtual string KeyGroup { get; set; }
public virtual string Key { get; set; }
public virtual string Value { get; set; }
}
}
流利的地图:
namespace Nop.Data.Mapping.Common
{
public partial class GenericAttributeMap : EntityTypeConfiguration<GenericAttribute>
{
public GenericAttributeMap()
{
ToTable("GenericAttribute");
HasKey(ga => ga.Id);
Property(ga => ga.KeyGroup).IsRequired().HasMaxLength(400);
Property(ga => ga.Key).IsRequired().HasMaxLength(400);
Property(ga => ga.Value).IsRequired();
}
}
}
要更新的代码:
prop = new GenericAttribute()
{
EntityId = entity.Id,
Key = key,
KeyGroup = keyGroup,
Value = valueStr
};
// calls _repository.Insert(), which then calls _context.SaveChanges();
InsertAttribute(prop);
Profiler 仅显示 SELECT,没有 INSERT 尝试:
{SELECT
[Extent1].[Id] AS [Id],
[Extent1].[EntityId] AS [EntityId],
[Extent1].[KeyGroup] AS [KeyGroup],
[Extent1].[Key] AS [Key],
[Extent1].[Value] AS [Value]
FROM [dbo].[GenericAttribute] AS [Extent1]}
【问题讨论】:
-
我怀疑 EF 会通过 Id 本身,所以它根本不会询问 DBMS。使用 fluent API 和 Property(x=>x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);解决这个问题。
-
@DevilSuichiro 我刚试过,同样的错误。
-
您可以使用分析器并验证正在生成的 SQL 吗?
-
@DrewJordan Profiler 不显示任何
INSERTs,仅显示SELECTs。我已将其添加到帖子中。 -
@Vaindil 你可以试试 Database.Log 来捕获插入语句吗?
标签: c# sql-server entity-framework