DB default value ignored when creating Entity Framework model

c# ef-database-first entity-framework entity-framework-6 sql-server

Question

Assuming I have the following table in my DB:

CREATE TABLE [dbo].[Test]
(
    [Id]      INT            IDENTITY (1, 1) NOT NULL,
    [Active]  BIT            DEFAULT ((1)) NOT NULL,
)

When creating an EF model from this DB, the mapping for the Active bit column, which is mapped to a Boolean column, has no default value (see property "Default Value): Property View - Model Diagram

Why does Entity Framework behave that way? Why doesn't the default value that is defined in the database automatically be applied in the model when the model gets created? The DB states that the default value should be 1, which I assumed would be a default value of true in the model. Do I really have to set the default value for all my columns in the model again?

I checked this behaviour for int and bit columns.


I did some more investigation, and tried to set the "Default Value" property by hand to True and true, and both works.

Manually changed default value

The auto-generated constructor for the Test-entity changes from

public Test()
{
}

to

public Test()
{
    this.Active = true;
}

So default values would be possible in EF, but they are not set when generating the model based on database-first, at least not on my machine.

So, the question still remains: Do I really have to set the default value for all my columns in the model again, even if they are already set in the DB?

1
4
10/29/2016 9:39:29 AM

Popular Answer

Try this:

StoreGeneratedPattern = Calculated

Edit:

Sorry for the one-code-line answer but I really was in a hurry last day.

To make EF set a property’s db default value, the fastest way is to open your .edmx designer, click on the interested field and set

StoreGeneratedPattern = Calculated

In its properties (you can see this property in your second screenshot, where you set “default value” to true).

3
10/1/2017 2:25:42 PM


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