如何使用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