EntityFramework Code First FluentAPI DefaultValue in EF6.X

感情迁移 提交于 2019-12-21 06:47:05

问题


How can I set the default value using EntityFramework Code First FluentAPI for bool property?

Something like:

Property(l => l.PropertyFlag).HasColumnType("bit").DefaultValue(1);

回答1:


Good news, code first now supports this. In the "Up()" method of the generated migration, specify a default with the following syntax:

AddColumn("[table name]", "[column name]", c => c.Boolean(nullable: false, defaultValue: false));

MSDN for "AddColumn" method




回答2:


I'm not sure about a fluent way, but you can simply set the property in a parameterless constructor...

public class MyTable
{
    public MyTable()
    {
        CanSetDefault = true;
    }

    public bool CanSetDefault {get; set; }
}

Update

A quick google suggests it is not possible using the fluent api...
http://social.msdn.microsoft.com/Forums/en-US/ad854e28-02f5-451b-9000-c8bcb1355d0b/codefirst-ctp5-and-default-values?forum=adonetefx




回答3:


Another option here is to override the default SqlServerMigrationSqlGenerator class with your own. You can then inject certain things you want to happen in the Generate method (for example, default values). The nice things with this is that you can also use this in other applications as it is pretty generic. Here is a good explanation on it.

 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()";
        }
    }


}



回答4:


Since EF doesn't have the functions I need, such as default values and unique key as foreign keys, we have to change the ORM from EF to NHibernate. It seems to me that NHibernate has more functions than EF 6.X.



来源:https://stackoverflow.com/questions/20199382/entityframework-code-first-fluentapi-defaultvalue-in-ef6-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!