Question

I just started experimenting with Entity Framework. I have created a table like so:

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

I also set

K__ID

to be the primary key.

Back in my business tier, when I run the following code,

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();

I get a

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.

error. SQL Profiling reveals the following RPC being sent to 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'

For your information, backing code for the above is like so:

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());
        }
    }
}
Was it helpful?

Solution

According your SQL insert statement EF thinks K__ID is an identity column which is wrong. Specify HasDatabaseGeneratedOption with None in the following line in your mapping:

Property(t => t.K__ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top