EntityFramework Code First FluentAPI DefaultValue in EF6.X












29















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);









share|improve this question

























  • possible duplicate of How can set a default value constraint with Entity Framework 6 Code First?

    – Colin
    Nov 25 '13 at 20:10











  • There should be some kind of solution for this issue, not just simple "No". I am talking all possible solutions.

    – Tony Bao
    Nov 25 '13 at 21:32






  • 1





    Sorry, I hadn't realised that. I thought you were looking for how to set the default value using EntityFramework Code First FluentAPI for bool property. How foolish of me ;-)

    – Colin
    Nov 26 '13 at 13:40
















29















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);









share|improve this question

























  • possible duplicate of How can set a default value constraint with Entity Framework 6 Code First?

    – Colin
    Nov 25 '13 at 20:10











  • There should be some kind of solution for this issue, not just simple "No". I am talking all possible solutions.

    – Tony Bao
    Nov 25 '13 at 21:32






  • 1





    Sorry, I hadn't realised that. I thought you were looking for how to set the default value using EntityFramework Code First FluentAPI for bool property. How foolish of me ;-)

    – Colin
    Nov 26 '13 at 13:40














29












29








29


2






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);









share|improve this question
















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);






c# entity-framework ef-code-first ef-fluent-api






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 21 '15 at 20:57









abatishchev

70.2k70266397




70.2k70266397










asked Nov 25 '13 at 17:28









Tony BaoTony Bao

4442921




4442921













  • possible duplicate of How can set a default value constraint with Entity Framework 6 Code First?

    – Colin
    Nov 25 '13 at 20:10











  • There should be some kind of solution for this issue, not just simple "No". I am talking all possible solutions.

    – Tony Bao
    Nov 25 '13 at 21:32






  • 1





    Sorry, I hadn't realised that. I thought you were looking for how to set the default value using EntityFramework Code First FluentAPI for bool property. How foolish of me ;-)

    – Colin
    Nov 26 '13 at 13:40



















  • possible duplicate of How can set a default value constraint with Entity Framework 6 Code First?

    – Colin
    Nov 25 '13 at 20:10











  • There should be some kind of solution for this issue, not just simple "No". I am talking all possible solutions.

    – Tony Bao
    Nov 25 '13 at 21:32






  • 1





    Sorry, I hadn't realised that. I thought you were looking for how to set the default value using EntityFramework Code First FluentAPI for bool property. How foolish of me ;-)

    – Colin
    Nov 26 '13 at 13:40

















possible duplicate of How can set a default value constraint with Entity Framework 6 Code First?

– Colin
Nov 25 '13 at 20:10





possible duplicate of How can set a default value constraint with Entity Framework 6 Code First?

– Colin
Nov 25 '13 at 20:10













There should be some kind of solution for this issue, not just simple "No". I am talking all possible solutions.

– Tony Bao
Nov 25 '13 at 21:32





There should be some kind of solution for this issue, not just simple "No". I am talking all possible solutions.

– Tony Bao
Nov 25 '13 at 21:32




1




1





Sorry, I hadn't realised that. I thought you were looking for how to set the default value using EntityFramework Code First FluentAPI for bool property. How foolish of me ;-)

– Colin
Nov 26 '13 at 13:40





Sorry, I hadn't realised that. I thought you were looking for how to set the default value using EntityFramework Code First FluentAPI for bool property. How foolish of me ;-)

– Colin
Nov 26 '13 at 13:40












5 Answers
5






active

oldest

votes


















29














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






share|improve this answer


























  • Link to more info?

    – joelmdev
    Mar 12 '14 at 16:19






  • 1





    @joelmdev Added a link to MSDN documentation

    – htxryan
    Mar 12 '14 at 21:15






  • 2





    This is only an Up migration. The OP is asking for how to set defaults at time of insert. Behind-the-scenes, EF maps every property in the POCO into the Insert statement as a NULL if the C# property is null. For value types, it inserts the value types default value. Useful info, though!

    – John Zabroski
    Sep 4 '14 at 3:20






  • 3





    The downside is that you have to remember to re-add this peice of code if you re-scafold your migration. Hopefully they will support this function in Fluent Api soon.

    – FatAlbert
    Apr 21 '15 at 8:43



















9














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






share|improve this answer



















  • 2





    Good suggestion, but doesn't work for DateTime.Now which is used for CreatedOn fields, as you will have clock drift from the time the class instance is constructed to when it is inserted. This would lead to some hard-to-debug code based on audit logs.

    – John Zabroski
    Sep 4 '14 at 3:21













  • This is now being worked on for EF7 and available in pre-release data.uservoice.com/forums/…

    – James Reategui
    Feb 18 '15 at 17:57













  • This only works for entries added with this. If you have existing entries, and you are adding a column to your schema, this doesn't work.

    – Warrick
    May 11 '17 at 3:03



















1














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.






share|improve this answer































    1














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


    }





    share|improve this answer
























    • Full explanation: andy.mehalick.com/2014/02/06/…

      – jwatts1980
      Sep 24 '17 at 5:58





















    0














    See example below



    class MyContext : DbContext
    {
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    modelBuilder.Entity<Blog>()
    .Property(b => b.Rating)
    .HasDefaultValue(3);
    }
    }

    public class Blog
    {
    public int BlogId { get; set; }
    public string Url { get; set; }
    public int Rating { get; set; }
    }





    share|improve this answer
























    • try to explain how and why your example works, maybe read How to Answer

      – LuckyLikey
      Nov 28 '18 at 14:46











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20199382%2fentityframework-code-first-fluentapi-defaultvalue-in-ef6-x%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    29














    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






    share|improve this answer


























    • Link to more info?

      – joelmdev
      Mar 12 '14 at 16:19






    • 1





      @joelmdev Added a link to MSDN documentation

      – htxryan
      Mar 12 '14 at 21:15






    • 2





      This is only an Up migration. The OP is asking for how to set defaults at time of insert. Behind-the-scenes, EF maps every property in the POCO into the Insert statement as a NULL if the C# property is null. For value types, it inserts the value types default value. Useful info, though!

      – John Zabroski
      Sep 4 '14 at 3:20






    • 3





      The downside is that you have to remember to re-add this peice of code if you re-scafold your migration. Hopefully they will support this function in Fluent Api soon.

      – FatAlbert
      Apr 21 '15 at 8:43
















    29














    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






    share|improve this answer


























    • Link to more info?

      – joelmdev
      Mar 12 '14 at 16:19






    • 1





      @joelmdev Added a link to MSDN documentation

      – htxryan
      Mar 12 '14 at 21:15






    • 2





      This is only an Up migration. The OP is asking for how to set defaults at time of insert. Behind-the-scenes, EF maps every property in the POCO into the Insert statement as a NULL if the C# property is null. For value types, it inserts the value types default value. Useful info, though!

      – John Zabroski
      Sep 4 '14 at 3:20






    • 3





      The downside is that you have to remember to re-add this peice of code if you re-scafold your migration. Hopefully they will support this function in Fluent Api soon.

      – FatAlbert
      Apr 21 '15 at 8:43














    29












    29








    29







    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






    share|improve this answer















    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







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 12 '14 at 21:06

























    answered Feb 11 '14 at 20:46









    htxryanhtxryan

    2,61911621




    2,61911621













    • Link to more info?

      – joelmdev
      Mar 12 '14 at 16:19






    • 1





      @joelmdev Added a link to MSDN documentation

      – htxryan
      Mar 12 '14 at 21:15






    • 2





      This is only an Up migration. The OP is asking for how to set defaults at time of insert. Behind-the-scenes, EF maps every property in the POCO into the Insert statement as a NULL if the C# property is null. For value types, it inserts the value types default value. Useful info, though!

      – John Zabroski
      Sep 4 '14 at 3:20






    • 3





      The downside is that you have to remember to re-add this peice of code if you re-scafold your migration. Hopefully they will support this function in Fluent Api soon.

      – FatAlbert
      Apr 21 '15 at 8:43



















    • Link to more info?

      – joelmdev
      Mar 12 '14 at 16:19






    • 1





      @joelmdev Added a link to MSDN documentation

      – htxryan
      Mar 12 '14 at 21:15






    • 2





      This is only an Up migration. The OP is asking for how to set defaults at time of insert. Behind-the-scenes, EF maps every property in the POCO into the Insert statement as a NULL if the C# property is null. For value types, it inserts the value types default value. Useful info, though!

      – John Zabroski
      Sep 4 '14 at 3:20






    • 3





      The downside is that you have to remember to re-add this peice of code if you re-scafold your migration. Hopefully they will support this function in Fluent Api soon.

      – FatAlbert
      Apr 21 '15 at 8:43

















    Link to more info?

    – joelmdev
    Mar 12 '14 at 16:19





    Link to more info?

    – joelmdev
    Mar 12 '14 at 16:19




    1




    1





    @joelmdev Added a link to MSDN documentation

    – htxryan
    Mar 12 '14 at 21:15





    @joelmdev Added a link to MSDN documentation

    – htxryan
    Mar 12 '14 at 21:15




    2




    2





    This is only an Up migration. The OP is asking for how to set defaults at time of insert. Behind-the-scenes, EF maps every property in the POCO into the Insert statement as a NULL if the C# property is null. For value types, it inserts the value types default value. Useful info, though!

    – John Zabroski
    Sep 4 '14 at 3:20





    This is only an Up migration. The OP is asking for how to set defaults at time of insert. Behind-the-scenes, EF maps every property in the POCO into the Insert statement as a NULL if the C# property is null. For value types, it inserts the value types default value. Useful info, though!

    – John Zabroski
    Sep 4 '14 at 3:20




    3




    3





    The downside is that you have to remember to re-add this peice of code if you re-scafold your migration. Hopefully they will support this function in Fluent Api soon.

    – FatAlbert
    Apr 21 '15 at 8:43





    The downside is that you have to remember to re-add this peice of code if you re-scafold your migration. Hopefully they will support this function in Fluent Api soon.

    – FatAlbert
    Apr 21 '15 at 8:43













    9














    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






    share|improve this answer



















    • 2





      Good suggestion, but doesn't work for DateTime.Now which is used for CreatedOn fields, as you will have clock drift from the time the class instance is constructed to when it is inserted. This would lead to some hard-to-debug code based on audit logs.

      – John Zabroski
      Sep 4 '14 at 3:21













    • This is now being worked on for EF7 and available in pre-release data.uservoice.com/forums/…

      – James Reategui
      Feb 18 '15 at 17:57













    • This only works for entries added with this. If you have existing entries, and you are adding a column to your schema, this doesn't work.

      – Warrick
      May 11 '17 at 3:03
















    9














    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






    share|improve this answer



















    • 2





      Good suggestion, but doesn't work for DateTime.Now which is used for CreatedOn fields, as you will have clock drift from the time the class instance is constructed to when it is inserted. This would lead to some hard-to-debug code based on audit logs.

      – John Zabroski
      Sep 4 '14 at 3:21













    • This is now being worked on for EF7 and available in pre-release data.uservoice.com/forums/…

      – James Reategui
      Feb 18 '15 at 17:57













    • This only works for entries added with this. If you have existing entries, and you are adding a column to your schema, this doesn't work.

      – Warrick
      May 11 '17 at 3:03














    9












    9








    9







    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






    share|improve this answer













    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







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 25 '13 at 17:49









    NinjaNyeNinjaNye

    5,89012742




    5,89012742








    • 2





      Good suggestion, but doesn't work for DateTime.Now which is used for CreatedOn fields, as you will have clock drift from the time the class instance is constructed to when it is inserted. This would lead to some hard-to-debug code based on audit logs.

      – John Zabroski
      Sep 4 '14 at 3:21













    • This is now being worked on for EF7 and available in pre-release data.uservoice.com/forums/…

      – James Reategui
      Feb 18 '15 at 17:57













    • This only works for entries added with this. If you have existing entries, and you are adding a column to your schema, this doesn't work.

      – Warrick
      May 11 '17 at 3:03














    • 2





      Good suggestion, but doesn't work for DateTime.Now which is used for CreatedOn fields, as you will have clock drift from the time the class instance is constructed to when it is inserted. This would lead to some hard-to-debug code based on audit logs.

      – John Zabroski
      Sep 4 '14 at 3:21













    • This is now being worked on for EF7 and available in pre-release data.uservoice.com/forums/…

      – James Reategui
      Feb 18 '15 at 17:57













    • This only works for entries added with this. If you have existing entries, and you are adding a column to your schema, this doesn't work.

      – Warrick
      May 11 '17 at 3:03








    2




    2





    Good suggestion, but doesn't work for DateTime.Now which is used for CreatedOn fields, as you will have clock drift from the time the class instance is constructed to when it is inserted. This would lead to some hard-to-debug code based on audit logs.

    – John Zabroski
    Sep 4 '14 at 3:21







    Good suggestion, but doesn't work for DateTime.Now which is used for CreatedOn fields, as you will have clock drift from the time the class instance is constructed to when it is inserted. This would lead to some hard-to-debug code based on audit logs.

    – John Zabroski
    Sep 4 '14 at 3:21















    This is now being worked on for EF7 and available in pre-release data.uservoice.com/forums/…

    – James Reategui
    Feb 18 '15 at 17:57







    This is now being worked on for EF7 and available in pre-release data.uservoice.com/forums/…

    – James Reategui
    Feb 18 '15 at 17:57















    This only works for entries added with this. If you have existing entries, and you are adding a column to your schema, this doesn't work.

    – Warrick
    May 11 '17 at 3:03





    This only works for entries added with this. If you have existing entries, and you are adding a column to your schema, this doesn't work.

    – Warrick
    May 11 '17 at 3:03











    1














    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.






    share|improve this answer




























      1














      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.






      share|improve this answer


























        1












        1








        1







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 26 '14 at 0:19









        Tony BaoTony Bao

        4442921




        4442921























            1














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


            }





            share|improve this answer
























            • Full explanation: andy.mehalick.com/2014/02/06/…

              – jwatts1980
              Sep 24 '17 at 5:58


















            1














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


            }





            share|improve this answer
























            • Full explanation: andy.mehalick.com/2014/02/06/…

              – jwatts1980
              Sep 24 '17 at 5:58
















            1












            1








            1







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


            }





            share|improve this answer













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


            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 1 '15 at 14:01









            gcoleman0828gcoleman0828

            85832747




            85832747













            • Full explanation: andy.mehalick.com/2014/02/06/…

              – jwatts1980
              Sep 24 '17 at 5:58





















            • Full explanation: andy.mehalick.com/2014/02/06/…

              – jwatts1980
              Sep 24 '17 at 5:58



















            Full explanation: andy.mehalick.com/2014/02/06/…

            – jwatts1980
            Sep 24 '17 at 5:58







            Full explanation: andy.mehalick.com/2014/02/06/…

            – jwatts1980
            Sep 24 '17 at 5:58













            0














            See example below



            class MyContext : DbContext
            {
            public DbSet<Blog> Blogs { get; set; }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
            modelBuilder.Entity<Blog>()
            .Property(b => b.Rating)
            .HasDefaultValue(3);
            }
            }

            public class Blog
            {
            public int BlogId { get; set; }
            public string Url { get; set; }
            public int Rating { get; set; }
            }





            share|improve this answer
























            • try to explain how and why your example works, maybe read How to Answer

              – LuckyLikey
              Nov 28 '18 at 14:46
















            0














            See example below



            class MyContext : DbContext
            {
            public DbSet<Blog> Blogs { get; set; }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
            modelBuilder.Entity<Blog>()
            .Property(b => b.Rating)
            .HasDefaultValue(3);
            }
            }

            public class Blog
            {
            public int BlogId { get; set; }
            public string Url { get; set; }
            public int Rating { get; set; }
            }





            share|improve this answer
























            • try to explain how and why your example works, maybe read How to Answer

              – LuckyLikey
              Nov 28 '18 at 14:46














            0












            0








            0







            See example below



            class MyContext : DbContext
            {
            public DbSet<Blog> Blogs { get; set; }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
            modelBuilder.Entity<Blog>()
            .Property(b => b.Rating)
            .HasDefaultValue(3);
            }
            }

            public class Blog
            {
            public int BlogId { get; set; }
            public string Url { get; set; }
            public int Rating { get; set; }
            }





            share|improve this answer













            See example below



            class MyContext : DbContext
            {
            public DbSet<Blog> Blogs { get; set; }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
            modelBuilder.Entity<Blog>()
            .Property(b => b.Rating)
            .HasDefaultValue(3);
            }
            }

            public class Blog
            {
            public int BlogId { get; set; }
            public string Url { get; set; }
            public int Rating { get; set; }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 28 '18 at 14:27









            Stefan VargaStefan Varga

            314




            314













            • try to explain how and why your example works, maybe read How to Answer

              – LuckyLikey
              Nov 28 '18 at 14:46



















            • try to explain how and why your example works, maybe read How to Answer

              – LuckyLikey
              Nov 28 '18 at 14:46

















            try to explain how and why your example works, maybe read How to Answer

            – LuckyLikey
            Nov 28 '18 at 14:46





            try to explain how and why your example works, maybe read How to Answer

            – LuckyLikey
            Nov 28 '18 at 14:46


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20199382%2fentityframework-code-first-fluentapi-defaultvalue-in-ef6-x%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks