问题
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?
回答1:
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).
回答2:
This solution solve for all entities that has same property such as CreatedDateTime
public partial class MyEntities : ObjectContext
{
public override int SaveChanges(SaveOptions options)
{
this.DetectChanges();
foreach (var insert in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added))
{
if (insert.Entity.GetType().GetProperty("CreatedDateTime") != null && insert.Entity.GetType().GetProperty("CreatedDateTime").GetType().Name == "DateTime" && (DateTime)(insert.Entity.GetType().GetProperty("CreatedDateTime").GetValue(insert.Entity)) == DateTime.Parse("0001-01-01 00:00:00.0000000"))
insert.Entity.GetType().GetProperty("CreatedDateTime").SetValue(insert.Entity, DateTime.UtcNow, null);
}
return base.SaveChanges(options);
}
}
referance: https://stackoverflow.com/a/5965743/7731479
来源:https://stackoverflow.com/questions/40310675/db-default-value-ignored-when-creating-entity-framework-model