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):
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.
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?
Test t = new Test()
) would be filled with the default values. Soctx.Tests.Add(t); ctx.SaveChanges();
would result in a new entry in the database, containing an Test-entry withActive = 1
, becauseActive
"has not been set set manually" (like you said "only change what has to be changed") and therefore should use the default value. But it seems that's not how EF works... – Iced.sql
files along with the one the model generates:ExtraSQL.sql
andInitialData.sql
. "extra sql" are things like these default values; additional SQL rules that need to be applied that aren't easily done through EF. "initial data" is any data that needs to be in the system for it to function. Then I can execute the three scripts and immediately have a working system. – Cassaundra