.net 如何在实体框架中使用数据库中的默认列值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/584556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Default column value from DataBase in Entity Framework?
提问by
I have a Date column in table which has default value or binding as getutcdate(). I want to use this in entity framework.On generating EDM I was able to find "Default Value " property at column level but I think it is for hardcoded value.
我在表中有一个日期列,它具有默认值或绑定为 getutcdate()。我想在实体框架中使用它。在生成 EDM 时,我能够在列级别找到“默认值”属性,但我认为它用于硬编码值。
Please let me know how can I use default value specified in database.
请让我知道如何使用数据库中指定的默认值。
回答by Heather
Implementing the OnCreated event for the entity is the solution I have found. I had a Guid property that I wanted to be populated. By default it was being populated with all zeros (00000-0000-00000-etc). By adding the following to my partial class of the entity I was able to deal with the issue.
为实体实现 OnCreated 事件是我找到的解决方案。我有一个想要填充的 Guid 属性。默认情况下,它被填充为全零(00000-0000-00000-etc)。通过将以下内容添加到实体的部分类中,我能够解决这个问题。
partial void OnCreated()
{
Guid = Guid.NewGuid();
}
回答by crokusek
A problem with setting StoreGeneratedPattern = "Computed" or "Identity" is that they do not allow the client to ever provide a value. Running into this issue on inserts but also for updates.
设置 StoreGeneratedPattern = "Computed" 或 "Identity" 的一个问题是它们不允许客户端提供值。在插入和更新时遇到这个问题。
Seems like another option or two is needed for StoreGeneratedPattern so the database can at least see the user provided values but override it if need be. This would allow any existing DB insert or update triggers that update one field based on another field to work. For instance a DB trigger on an update might update the modified timestamp only if one is not provided and only if certain fields were updated.
似乎 StoreGeneratedPattern 需要另一个或两个选项,因此数据库至少可以看到用户提供的值,但如果需要可以覆盖它。这将允许任何现有的基于另一个字段更新一个字段的数据库插入或更新触发器工作。例如,更新时的数据库触发器可能仅在未提供时间戳且仅在更新某些字段时才更新修改后的时间戳。
Perhaps the column extended attributes feature in SQL Server could be used to set that field automatically during extraction so we don't end up editing XML files.
也许 SQL Server 中的列扩展属性功能可用于在提取期间自动设置该字段,这样我们就不会最终编辑 XML 文件。
回答by crokusek
StoreGeneratedPattern = "Computed" is not the same as a default value, because this property would be updated EVERY TIME with the default value in the database.. meaning it is impossible to update it manually.
StoreGeneratedPattern = "Computed" 与默认值不同,因为此属性将使用数据库中的默认值每次更新..意味着不可能手动更新它。
回答by mvr
You can set the StoreGeneratedPattern to Identity, in which case EF reads the value returned from the database after executing the INSERT statement. The problem with this approach is that the next time the XML mapping is generated, your change will be lost.
您可以将 StoreGeneratedPattern 设置为 Identity,在这种情况下,EF 在执行 INSERT 语句后读取从数据库返回的值。这种方法的问题在于,下次生成 XML 映射时,您的更改将丢失。
Another way to do it is to set the value yourself in your code to DateTime.UtcNow. You could set this in your entity's constructor (define a new constructor if necessary), or you could set it in your own event handler for your context's SavingChanges event (see How to: Execute Business Logic When Saving Changes (Entity Framework)for an example of handling the SavingChanges event).
另一种方法是自己在代码中将值设置为 DateTime.UtcNow。您可以在实体的构造函数中设置它(如有必要,定义一个新的构造函数),或者您可以在您自己的事件处理程序中为上下文的 SavingChanges 事件设置它(参见如何:在保存更改时执行业务逻辑(实体框架)示例)处理 SavingChanges 事件)。
回答by NER1808
There is another solution suggested in this post by using a partial class and a method in the constructor to set the values.
这篇文章中提出了另一种解决方案,即在构造函数中使用分部类和方法来设置值。
How to use the default Entity Framework and default date values
回答by user6268526
It is pretty simple to create a partial class for the entity model(s), similar to what you do for data annotations. Then I override the default constructor and set the default properties in the constructor. Works like a charm.
为实体模型创建分部类非常简单,类似于您为数据注释所做的。然后我覆盖默认构造函数并在构造函数中设置默认属性。奇迹般有效。
public partial class CallHistoryLog
{
public CallHistoryLog()
{
this.NumberFromId = -1L;
this.NumberFromName = "NO NAME";
this.NumberToId = -1L;
this.NumberToName = "NO NAME";
this.RouteId = -1L;
this.Viewed = false;
this.Deleted = false;
this.DateCreated = DateTime.Now;
}
}
回答by Acorndog
Hmm... if you are using EF6, this is actually a lot easier than you might think. Just open your model, right click on the column you want to set a default for, choose properties, and you will see a "DefaultValue" field. Just fill that out and save. It will set up the code for you.
嗯...如果您使用的是 EF6,这实际上比您想象的要容易得多。只需打开您的模型,右键单击您要为其设置默认值的列,选择属性,您将看到一个“DefaultValue”字段。只需填写并保存即可。它将为您设置代码。
The problem with some of the other solutions, it that while they may work initially, as soon as you rebuild the model, it will throw out any custom code you inserted into the machine-generated file.
其他一些解决方案的问题是,虽然它们最初可能会起作用,但一旦您重建模型,它就会抛出您插入到机器生成的文件中的任何自定义代码。
So under the hood the UI works by adding an extra property to the edmx file:
所以在底层,UI 通过向 edmx 文件添加一个额外的属性来工作:
<EntityType Name="Thingy">
<Property Name="Iteration" Type="Int32" Nullable="false" **DefaultValue="1"** />
And by adding the necessary code to the constructor:
并通过向构造函数添加必要的代码:
public Thingy()
{
this.Iteration = 1;
回答by Marcelo Alves Godinho
Insert thats format:
插入格式:
//class
[Column("guid")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string guid_ { get; set; }
...
//end class
after the command yourContext.SaveChanges();
在命令 yourContext.SaveChanges() 之后;
You can see return default data from database in your class model.
您可以在类模型中看到从数据库返回的默认数据。
Good Look
好看
回答by Asaf R
Here's a possible, but not pretty workaround -
这是一个可能的,但不是很好的解决方法 -
Setting Computed on a column will make it read only, but will make the default value work. It's possible to have a real Computed column, say "LastChangedAt_computed" that either shows the value of "LastChangedAt_default" or "LastChangedAt_manual".
在列上设置 Computed 将使其只读,但会使默认值起作用。可能有一个真正的 Computed 列,比如“LastChangedAt_computed”,它显示“LastChangedAt_default”或“LastChangedAt_manual”的值。
Now, the computed column shows the value of the default column, unless the manual column is not-null, in which case it is shown. In the model, the StoragePattern of the default column needs to be "Computed".
现在,计算列显示默认列的值,除非手动列不为空,在这种情况下会显示它。在模型中,默认列的 StoragePattern 需要为“Computed”。
It's an ugly solution, but it should work.
这是一个丑陋的解决方案,但它应该有效。

