0

我刚开始尝试使用实体框架。我创建了一个像这样的表:

CREATE TABLE WORK_EFFORT
(
    K__ID BIGINT,
    NAME NTEXT,
    DESCRIPTION NTEXT
)

我也设置

K__ID

成为主键。

回到我的业务层,当我运行以下代码时,

var db = new ENTERPRISE_context();

var workEffort = new WORK_EFFORT
{
    K__ID = 1,
    NAME = "merhaba, dünya",
    DESCRIPTION = "merhaba, dünya"
};
db.WORK_EFFORT_set.Add(workEffort);

db.SaveChanges();

我得到一个

Cannot insert the value NULL into column 'K__ID', table 'ENTERPRISE.dbo.WORK_EFFORT'; column does not allow nulls. INSERT fails.
The statement has been terminated.

错误。SQL Profiling 显示以下 RPC 被发送到 SQL Server:

exec sp_executesql N'INSERT [dbo].[WORK_EFFORT]([NAME], [DESCRIPTION])
VALUES (@0, @1)
SELECT [K__ID]
FROM [dbo].[WORK_EFFORT]
WHERE @@ROWCOUNT > 0 AND [K__ID] = scope_identity()',N'@0 nvarchar(max) ,@1 nvarchar(max) ',@0=N'merhaba, dünya',@1=N'merhaba, dünya'

供您参考,上述支持代码如下所示:

namespace Web.Models
{
    public partial class WORK_EFFORT
    {
        public long K__ID { get; set; }    
        public string NAME { get; set; }
        public string DESCRIPTION { get; set; }
    }
}

namespace Web.Models.Mapping
{
    public partial class WORK_EFFORT_map : EntityTypeConfiguration<WORK_EFFORT>
    {
        public WORK_EFFORT_map()
        {
            this.HasKey(t => t.K__ID);

            this.ToTable("WORK_EFFORT");

            this.Property(t => t.K__ID).HasColumnName("K__ID");
            this.Property(t => t.NAME).HasColumnName("NAME");
            this.Property(t => t.DESCRIPTION).HasColumnName("DESCRIPTION");
        }
    }
}

namespace Web.Models
{
    public partial class ENTERPRISE_context : DbContext
    {
        static ENTERPRISE_context()
        {
            Database.SetInitializer<ENTERPRISE_context>(null);
        }

        public ENTERPRISE_context() : base("Name=ENTERPRISE_context") { }

        public DbSet<WORK_EFFORT> WORK_EFFORT_set { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new WORK_EFFORT_map());
        }
    }
}
4

1 回答 1

2

根据您的 SQL 插入语句,EF 认为 K__ID 是一个错误的标识列。在映射的以下行中将 HasDatabaseGeneratedOption 指定为 None:

Property(t => t.K__ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
于 2013-10-31T16:52:20.080 回答