创建实体框架模型时忽略数据库默认值 [英] DB default value ignored when creating Entity Framework model
问题描述
假设我的数据库中有下表:
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,
)
从该数据库创建EF模型时,映射到Boolean
列的Active
bit列的映射没有默认值(请参见属性默认值") :
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):
为什么实体框架会以这种方式运行?创建模型后,为什么不自动将数据库中定义的默认值应用到模型中? DB声明默认值应为1
,我假设该默认值应为模型中的true
.我真的必须再次为模型中的所有列设置默认值吗?
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?
我检查了 int 和 bit 列的行为.
我做了一些进一步的研究,并尝试将默认值"属性手动设置为True
和true
,两者均起作用.
I did some more investigation, and tried to set the "Default Value" property by hand to True
and true
, and both works.
自动生成的Test-entity构造函数更改为
The auto-generated constructor for the Test-entity changes from
public Test()
{
}
到
public Test()
{
this.Active = true;
}
因此在EF中可以使用默认值,但是在基于数据库优先(至少不是在我的机器上)生成模型时未设置默认值.
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?
推荐答案
尝试一下:
StoreGeneratedPattern = Calculated
很抱歉,只有一个代码行的答案,但我真的很着急.
Sorry for the one-code-line answer but I really was in a hurry last day.
要使EF设置属性的db默认值,最快的方法是打开.edmx设计器,单击感兴趣的字段并设置
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 =计算得出
StoreGeneratedPattern = Calculated
在其属性中(您可以在第二个屏幕快照中看到此属性,在该屏幕快照中,您将默认值"设置为true).
In its properties (you can see this property in your second screenshot, where you set "default value" to true).
这篇关于创建实体框架模型时忽略数据库默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!