实体框架保存更改():未发送主键列的值



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

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 分析显示以下 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());
        }
    }
}

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

Property(t => t.K__ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

相关内容

  • 没有找到相关文章

最新更新