2

When adding a record with EntityFramework Core, if I want to force a column which has a default value to another 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 Answer 1

2

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

modelBuilder.Entity<MyEntity>().Property(a => a.MyBool).ValueGeneratedNever();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.