无法将值NULL插入列' Id',列是标识和PK

时间:2015-11-02 16:17:07

标签: c# sql-server entity-framework

这个问题在SO上被问过很多次,但其他答案都没有帮助。我正在插入表格(SQL Server 2014,EF 6),并且我收到错误Cannot insert the value NULL into column 'Id' ... column does not allow nulls.我的数据库中设置了Id列作为主键AND是一个标识栏,我已经三次检查过。我能够插入而不在SSMS中使用T-SQL指定Id,但EF失败。它为值传递0;我不明白为什么它不被接受。我不使用任何数据注释,我只使用流畅的映射。

This answerthis 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]}

3 个答案:

答案 0 :(得分:0)

听起来像你错过了auto_increment栏中的设置。在你的桌子上看一下这样的东西:

MySQL的:

ALTER TABLE table_name MODIFY COLUMN coumn_name INT auto_increment

T-SQL:

ALTER TABLE table_name ADD column_name int NOT NULL IDENTITY (1,1) PRIMARY KEY

答案 1 :(得分:0)

尝试将以下内容添加到映射配置类

Property(ga => ga.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

答案 2 :(得分:0)

我对FluentAPI并不熟悉,但我的预感是,这源于你的继承层次结构:也就是说,它看到的NULL值实际上在EXPLAIN而不是joins本身。 This blog表示您应该使用父类的BaseEntity进行映射,而不是子类。它对数据库无关紧要,但EF可能会尝试在父级上找到实例。