[英]How does Entity Framework handle Default constraints in the database table?
I am working on code which I cannot run until it's finished, as it is a long and tedious process to go through. 我正在编写无法完成的代码,因为这是一个漫长而繁琐的过程。 I have been tasked to add a new table to the existing database, update the .edmx of the model and write a method to add new rows to the table through c# backend code.
我的任务是向现有数据库添加新表,更新模型的.edmx并编写一种方法,以通过c#后端代码向表中添加新行。
In my situation, I have 2 default constraints on my table 在我的情况下,我的表上有2个默认约束
SomeTable
------------
ID INT IDENTITY (1,1) PRIMARY KEY CLUSTERED,
SomeDate DATETIME2 NOT NULL DEFAULT GETDATE(),
SomeOtherField VARCHAR(1024) NOT NULL DEFAULT ''
Using the .edmx model of this table, I set SomeDate's StoreGeneratedPattern
to Computed
. 使用此表的.edmx模型,我将SomeDate的
StoreGeneratedPattern
设置为Computed
。 I also manually double-checked it in the SSDL
to ensure the computed StoreGeneratedPattern
attribute was on the SomeDate
Field in the SomeTable
entity. 我还手动在
SSDL
对其进行了双重检查,以确保computed StoreGeneratedPattern
属性位于SomeTable
实体的SomeDate
字段中。
As far as I know, and are unsure of, when I have a the following code 据我所知,不确定何时有以下代码
public void AddSomeRow(...)
{
SomeDbContext context = new SomeDbContext;
var table = new SomeTable { SomeOtherField = "Value" };
context.SomeTables.Add(table);
context.SaveChanges();
}
I believe the SomeDate
Field will be set to it's default constraint (because it hasn't been populated in the entity). 我相信
SomeDate
字段将设置为默认约束(因为尚未在实体中填充该字段)。 Is this true ? 这是真的吗?
Doing the same steps listed above for SomeOtherField
, can I still manually give it a value (the value appearing into that field instead of the Default Constraint) or omit it (The default constraint will be set into that field)? 对
SomeOtherField
上面列出的相同步骤, 我是否仍可以手动为它提供一个值(该值而不是默认约束出现在该字段中)或忽略它(默认约束将设置在该字段中)?
This question was hard to explain, I apologize if it doesn't make sense 这个问题很难解释,如果不合理,我深表歉意
The StoreGeneratedPattern
implies that the value is always generated by the DB, so that you're not allowed to modify it. StoreGeneratedPattern
表示该值始终由数据库生成,因此不允许您对其进行修改。 Ie it only makes sense for DB computed columns. 即,仅对数据库计算列有意义。
At least until EF 6.1 there is no direct way to support DB defaults. 至少在EF 6.1之前,还没有直接的方法来支持数据库默认值。 The only thing that you can do is move the default values out of the DB and generate them in the model (or code first) side.
您唯一可以做的就是将默认值移出数据库,并在模型(或代码优先)端生成它们。 You'll find some work-aounds but they're not safe for some cases (specially for N-tier apps).
您会发现一些可行的方法,但是在某些情况下(特别是对于N层应用程序)它们并不安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.