问题描述
我正在尝试将 Code-First EF6 与默认 SQL 值一起使用.
I am trying to use Code-First EF6 with default SQL values.
例如,我有一个CreatedDate"列/属性不为空,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 在尚未设置时不会发送值:
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
实现类似功能的公认方法是将 Computed
属性与 Migrations
一起使用,您可以在其中指定默认数据库函数.
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; }
}
计算的属性不必是可空的.
The computed property doesn't have to be nullable.
然后您必须运行迁移并手动修改它以包含默认 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 列默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!