如何使用EntityFramework Code First FluentAPI为bool属性设置默认值?EntityFramework代码EF6.X中的第一个FluentAPI DefaultValue
喜欢的东西:
Property(l => l.PropertyFlag).HasColumnType("bit").DefaultValue(1);
如何使用EntityFramework Code First FluentAPI为bool属性设置默认值?EntityFramework代码EF6.X中的第一个FluentAPI DefaultValue
喜欢的东西:
Property(l => l.PropertyFlag).HasColumnType("bit").DefaultValue(1);
我不知道能说一口流利的方式,但你可以简单地设置参数的构造函数的性质......
public class MyTable
{
public MyTable()
{
CanSetDefault = true;
}
public bool CanSetDefault {get; set; }
}
更新
快速谷歌表明它是不可能使用流利的API ...
http://social.msdn.microsoft.com/Forums/en-US/ad854e28-02f5-451b-9000-c8bcb1355d0b/codefirst-ctp5-and-default-values?forum=adonetefx
好的建议,但对于用于CreatedOn字段的DateTime.Now不起作用,因为从类实例的构建时间到插入时间,都会有时钟漂移。这会导致一些基于审计日志的难以调试的代码。 –
现在正在为EF7工作,并在预发行版中提供https://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/2929682-support-database-default-values-in -code-first –
这只适用于与此相关的条目。如果您有现有条目,并且正在向模式添加列,则这不起作用。 – Warrick
由于EF没有我需要的函数,比如缺省值和唯一键作为外键,所以我们必须将ORM从EF更改为NHibernate。在我看来,NHibernate比EF 6.X有更多的功能。
好消息,代码现在首先支持这一点。在生成的迁移“向上()”方法,指定一个默认的语法如下:
AddColumn("[table name]", "[column name]", c => c.Boolean(nullable: false, defaultValue: false));
另一个选择是重写默认SqlServerMigrationSqlGenerator类自己。然后,您可以在Generate方法中注入想要发生的某些事情(例如,默认值)。这样做的好处是你可以在其他应用程序中使用它,因为它非常通用。 Here是一个很好的解释。
internal class CustomSqlServerMigrationSqlGenerator : SqlServerMigrationSqlGenerator
{
protected override void Generate(AddColumnOperation addColumnOperation)
{
SetCreatedUtcColumn(addColumnOperation.Column);
base.Generate(addColumnOperation);
}
protected override void Generate(CreateTableOperation createTableOperation)
{
SetCreatedUtcColumn(createTableOperation.Columns);
base.Generate(createTableOperation);
}
private static void SetCreatedUtcColumn(IEnumerable<ColumnModel> columns)
{
foreach (var columnModel in columns)
{
SetCreatedUtcColumn(columnModel);
}
}
private static void SetCreatedUtcColumn(PropertyModel column)
{
if (column.Name == "CreatedUtc")
{
column.DefaultValueSql = "GETUTCDATE()";
}
}
}
的
完整说明:https://andy.mehalick.com/2014/02/06/ef6-adding-a-created-datetime-column-automatically-with-code-first-migrations/ – jwatts1980
可能重复[如何设置与实体框架6码首先?默认值约束(http://stackoverflow.com/questions/20136504/how-can-set-a-default-value- constraint-with-entity-framework-6-code-first) – Colin
这个问题应该有一些解决方案,而不仅仅是简单的“否”。我在谈论所有可能的解决方案。 –
对不起,我没有意识到这一点。我以为你在寻找如何使用EntityFramework Code First FluentAPI为bool属性设置默认值。对我来说有多愚蠢;-) – Colin