SQL列默认值与实体框架 [英] SQL column default value with Entity Framework
问题描述
我试图使用默认SQL值的Code-First EF6。
I am trying to use Code-First EF6 with default SQL values.
例如,我有一个CreatedDate列/属性not null,SQL中的默认值为getdate()
For example, I have a "CreatedDate" column/property not null with a default in SQL of "getdate()"
如何在我的代码模型中代表这个?目前我有:
How do I represent this in my code Model? Currently I have:
<DatabaseGenerated(DatabaseGeneratedOption.Computed)>
Public Property CreatedDate As DateTime
这是否工作,或者我需要使用可空即使实际的列不应该为空,所以当EF未设置时,EF不会发送一个值:
Will this work, or will I need to use a nullable even though the actual column should be not null, so EF doesn't send a value when it hasn't been set:
<DatabaseGenerated(DatabaseGeneratedOption.Computed)>
Public Property CreatedDate As DateTime?
还是有更好的解决方案?
Or is there a better solution out there?
我不希望EF处理我的默认值 - 我知道这是可用的,但我目前的情况是不可能的。
I don't want EF to handle my defaults - I know this is available to me but not possible in my current situation.
推荐答案
目前在EF6中没有定义用于特定属性默认值的数据库函数的属性。您可以对Codeplex进行投票,以实现它:
Currently in EF6 there is not an attribute to define database functions used for a certain property default value. You can vote on Codeplex to get it implemented:
https:// entityframework .codeplex.com / workitem / 44
实现类似的方法是使用计算的
属性与迁移
您指定默认数据库函数。
The accepted way to implement something like that is to use Computed
properties with Migrations
where you specify the default database function.
您的课程可能在C#中看起来像这样:
Your class could look like this in C#:
public class MyEntity
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime Created { get; set; }
}
计算的属性不必为空。
然后您必须运行迁移并手动修改它以包括默认的SQL函数。迁移可能如下所示:
Then you have to run a migration and modify it by hand to include the default SQL function. A migration could look like:
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.MyEntities",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Created = c.DateTime(nullable: false, defaultValueSql: "GetDate()"),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.MyEntities");
}
}
您将注意到defaultValueSql函数。这是获得计算工作的关键
You will notice the defaultValueSql function. That is the key to get the computation working
这篇关于SQL列默认值与实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!