How to force default values in an insert with EntityFramework core?

.net-core c# entity-framework-core sql sql-server

Question

When adding a record with EntityFramework Core, if I want to force a column wich has a default value to annother value, the default value is taken.

SQL

CREATE TABLE MyEntity(
    Id INT IDENTITY(1,1) NOT NULL, 
    MyProperty1 VARCHAR(50),
    MyBool BIT NOT NULL DEFAULT 1
);

.NET

public void insertNewMyEntity()
{
    MyEntity me = New MyEntity();
    me.MyProperty1 = "Testing insert and default values with EF Core";
    me.MyBool = 0;
    dbContext.MyEntity.Add(me);
    dbContext.SaveChanges();
}

In the Database, there's MyBool = 1 because EntityFramework send the following command :

INSERT INTO MyEntity(MyProperty1) VALUES ("Testing insert and default values with EF Core");

Instead of :

INSERT INTO MyEntity(MyProperty1, MyBool) VALUES ("Testing insert and default values with EF Core", 0);

I could add data annotation [DataGenerated(DataGeneratedOption.None)] on MyBool but I don't want to redo all the data annotations in all entities after each classes generation with EF.

1
2
11/17/2016 1:17:26 PM

Accepted Answer

I add data annotation [DataGenerated(DataGeneratedOption.None)] on the properties with the configBuilder object :

modelBuilder.Entity<MyEntity>().Property(a => a.MyBool).ValueGeneratedNever();
2
12/22/2016 8:28:14 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow