SQL column default value with Entity Framework












9















I am trying to use Code-First EF6 with default SQL values.



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


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?



I don't want EF to handle my defaults - I know this is available to me but not possible in my current situation.










share|improve this question



























    9















    I am trying to use Code-First EF6 with default SQL values.



    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


    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?



    I don't want EF to handle my defaults - I know this is available to me but not possible in my current situation.










    share|improve this question

























      9












      9








      9


      1






      I am trying to use Code-First EF6 with default SQL values.



      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


      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?



      I don't want EF to handle my defaults - I know this is available to me but not possible in my current situation.










      share|improve this question














      I am trying to use Code-First EF6 with default SQL values.



      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


      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?



      I don't want EF to handle my defaults - I know this is available to me but not possible in my current situation.







      .net entity-framework entity-framework-6






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '14 at 11:31









      CarlCarl

      1,665922




      1,665922
























          2 Answers
          2






          active

          oldest

          votes


















          17














          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



          The accepted way to implement something like that is to use Computed properties with Migrations where you specify the default database function.



          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.



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


          You will notice the defaultValueSql function. That is the key to get the computation working






          share|improve this answer


























          • Great, thanks, I will go with this for now.

            – Carl
            Nov 20 '14 at 17:01











          • You are welcome ;)

            – Faris Zacina
            Nov 20 '14 at 17:01



















          3














          Accepted answer is correct for EF6, I'm only adding EF Core solution; (also my solution focuses on changing the default-value, rather than creating it properly the first time)



          There is still no Data-Attribute in EF Core.



          And you must still use the Fluent API; it does have a HasDefaultValue



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


          Note, there is also HasDefaultValueSql for NULL case:



                  .HasDefaultValueSql("NULL");


          And you can also use the Migrations Up and Down methods, you can alter the defaultValue or defaultValueSql but you may need to drop Indexes first. Here's an example:



          public partial class RemovingDefaultToZeroPlantIdManualChange : Migration
          {
          protected override void Up(MigrationBuilder migrationBuilder)
          {
          migrationBuilder.DropIndex(
          name: "IX_TABLE_NAME_COLUMN_NAME",
          table: "TABLE_NAME"
          );

          migrationBuilder.AlterColumn<int>(
          name: "COLUMN_NAME",
          table: "TABLE_NAME",
          nullable: true,
          //note here, in the Up method, I'm specifying a new defaultValue:
          defaultValueSql: "NULL",
          oldClrType: typeof(int));

          migrationBuilder.CreateIndex(
          name: "IX_TABLE_NAME_COLUMN_NAME",
          table: "TABLE_NAME",
          column: "COLUMN_NAME"
          );
          }

          protected override void Down(MigrationBuilder migrationBuilder)
          {
          migrationBuilder.DropIndex(
          name: "IX_TABLE_NAME_COLUMN_NAME",
          table: "TABLE_NAME"
          );

          migrationBuilder.AlterColumn<int>(
          name: "COLUMN_NAME",
          table: "TABLE_NAME",
          nullable: true,
          //note here, in the Down method, I'll restore to the old defaultValue:
          defaultValueSql: "0",
          oldClrType: typeof(int));

          migrationBuilder.CreateIndex(
          name: "IX_TABLE_NAME_COLUMN_NAME",
          table: "TABLE_NAME",
          column: "COLUMN_NAME"
          );


          }
          }





          share|improve this answer

























            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%2f27038524%2fsql-column-default-value-with-entity-framework%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            17














            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



            The accepted way to implement something like that is to use Computed properties with Migrations where you specify the default database function.



            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.



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


            You will notice the defaultValueSql function. That is the key to get the computation working






            share|improve this answer


























            • Great, thanks, I will go with this for now.

              – Carl
              Nov 20 '14 at 17:01











            • You are welcome ;)

              – Faris Zacina
              Nov 20 '14 at 17:01
















            17














            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



            The accepted way to implement something like that is to use Computed properties with Migrations where you specify the default database function.



            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.



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


            You will notice the defaultValueSql function. That is the key to get the computation working






            share|improve this answer


























            • Great, thanks, I will go with this for now.

              – Carl
              Nov 20 '14 at 17:01











            • You are welcome ;)

              – Faris Zacina
              Nov 20 '14 at 17:01














            17












            17








            17







            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



            The accepted way to implement something like that is to use Computed properties with Migrations where you specify the default database function.



            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.



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


            You will notice the defaultValueSql function. That is the key to get the computation working






            share|improve this answer















            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



            The accepted way to implement something like that is to use Computed properties with Migrations where you specify the default database function.



            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.



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


            You will notice the defaultValueSql function. That is the key to get the computation working







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 20 '14 at 17:02

























            answered Nov 20 '14 at 12:33









            Faris ZacinaFaris Zacina

            10.4k74064




            10.4k74064













            • Great, thanks, I will go with this for now.

              – Carl
              Nov 20 '14 at 17:01











            • You are welcome ;)

              – Faris Zacina
              Nov 20 '14 at 17:01



















            • Great, thanks, I will go with this for now.

              – Carl
              Nov 20 '14 at 17:01











            • You are welcome ;)

              – Faris Zacina
              Nov 20 '14 at 17:01

















            Great, thanks, I will go with this for now.

            – Carl
            Nov 20 '14 at 17:01





            Great, thanks, I will go with this for now.

            – Carl
            Nov 20 '14 at 17:01













            You are welcome ;)

            – Faris Zacina
            Nov 20 '14 at 17:01





            You are welcome ;)

            – Faris Zacina
            Nov 20 '14 at 17:01













            3














            Accepted answer is correct for EF6, I'm only adding EF Core solution; (also my solution focuses on changing the default-value, rather than creating it properly the first time)



            There is still no Data-Attribute in EF Core.



            And you must still use the Fluent API; it does have a HasDefaultValue



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


            Note, there is also HasDefaultValueSql for NULL case:



                    .HasDefaultValueSql("NULL");


            And you can also use the Migrations Up and Down methods, you can alter the defaultValue or defaultValueSql but you may need to drop Indexes first. Here's an example:



            public partial class RemovingDefaultToZeroPlantIdManualChange : Migration
            {
            protected override void Up(MigrationBuilder migrationBuilder)
            {
            migrationBuilder.DropIndex(
            name: "IX_TABLE_NAME_COLUMN_NAME",
            table: "TABLE_NAME"
            );

            migrationBuilder.AlterColumn<int>(
            name: "COLUMN_NAME",
            table: "TABLE_NAME",
            nullable: true,
            //note here, in the Up method, I'm specifying a new defaultValue:
            defaultValueSql: "NULL",
            oldClrType: typeof(int));

            migrationBuilder.CreateIndex(
            name: "IX_TABLE_NAME_COLUMN_NAME",
            table: "TABLE_NAME",
            column: "COLUMN_NAME"
            );
            }

            protected override void Down(MigrationBuilder migrationBuilder)
            {
            migrationBuilder.DropIndex(
            name: "IX_TABLE_NAME_COLUMN_NAME",
            table: "TABLE_NAME"
            );

            migrationBuilder.AlterColumn<int>(
            name: "COLUMN_NAME",
            table: "TABLE_NAME",
            nullable: true,
            //note here, in the Down method, I'll restore to the old defaultValue:
            defaultValueSql: "0",
            oldClrType: typeof(int));

            migrationBuilder.CreateIndex(
            name: "IX_TABLE_NAME_COLUMN_NAME",
            table: "TABLE_NAME",
            column: "COLUMN_NAME"
            );


            }
            }





            share|improve this answer






























              3














              Accepted answer is correct for EF6, I'm only adding EF Core solution; (also my solution focuses on changing the default-value, rather than creating it properly the first time)



              There is still no Data-Attribute in EF Core.



              And you must still use the Fluent API; it does have a HasDefaultValue



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


              Note, there is also HasDefaultValueSql for NULL case:



                      .HasDefaultValueSql("NULL");


              And you can also use the Migrations Up and Down methods, you can alter the defaultValue or defaultValueSql but you may need to drop Indexes first. Here's an example:



              public partial class RemovingDefaultToZeroPlantIdManualChange : Migration
              {
              protected override void Up(MigrationBuilder migrationBuilder)
              {
              migrationBuilder.DropIndex(
              name: "IX_TABLE_NAME_COLUMN_NAME",
              table: "TABLE_NAME"
              );

              migrationBuilder.AlterColumn<int>(
              name: "COLUMN_NAME",
              table: "TABLE_NAME",
              nullable: true,
              //note here, in the Up method, I'm specifying a new defaultValue:
              defaultValueSql: "NULL",
              oldClrType: typeof(int));

              migrationBuilder.CreateIndex(
              name: "IX_TABLE_NAME_COLUMN_NAME",
              table: "TABLE_NAME",
              column: "COLUMN_NAME"
              );
              }

              protected override void Down(MigrationBuilder migrationBuilder)
              {
              migrationBuilder.DropIndex(
              name: "IX_TABLE_NAME_COLUMN_NAME",
              table: "TABLE_NAME"
              );

              migrationBuilder.AlterColumn<int>(
              name: "COLUMN_NAME",
              table: "TABLE_NAME",
              nullable: true,
              //note here, in the Down method, I'll restore to the old defaultValue:
              defaultValueSql: "0",
              oldClrType: typeof(int));

              migrationBuilder.CreateIndex(
              name: "IX_TABLE_NAME_COLUMN_NAME",
              table: "TABLE_NAME",
              column: "COLUMN_NAME"
              );


              }
              }





              share|improve this answer




























                3












                3








                3







                Accepted answer is correct for EF6, I'm only adding EF Core solution; (also my solution focuses on changing the default-value, rather than creating it properly the first time)



                There is still no Data-Attribute in EF Core.



                And you must still use the Fluent API; it does have a HasDefaultValue



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


                Note, there is also HasDefaultValueSql for NULL case:



                        .HasDefaultValueSql("NULL");


                And you can also use the Migrations Up and Down methods, you can alter the defaultValue or defaultValueSql but you may need to drop Indexes first. Here's an example:



                public partial class RemovingDefaultToZeroPlantIdManualChange : Migration
                {
                protected override void Up(MigrationBuilder migrationBuilder)
                {
                migrationBuilder.DropIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME"
                );

                migrationBuilder.AlterColumn<int>(
                name: "COLUMN_NAME",
                table: "TABLE_NAME",
                nullable: true,
                //note here, in the Up method, I'm specifying a new defaultValue:
                defaultValueSql: "NULL",
                oldClrType: typeof(int));

                migrationBuilder.CreateIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME",
                column: "COLUMN_NAME"
                );
                }

                protected override void Down(MigrationBuilder migrationBuilder)
                {
                migrationBuilder.DropIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME"
                );

                migrationBuilder.AlterColumn<int>(
                name: "COLUMN_NAME",
                table: "TABLE_NAME",
                nullable: true,
                //note here, in the Down method, I'll restore to the old defaultValue:
                defaultValueSql: "0",
                oldClrType: typeof(int));

                migrationBuilder.CreateIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME",
                column: "COLUMN_NAME"
                );


                }
                }





                share|improve this answer















                Accepted answer is correct for EF6, I'm only adding EF Core solution; (also my solution focuses on changing the default-value, rather than creating it properly the first time)



                There is still no Data-Attribute in EF Core.



                And you must still use the Fluent API; it does have a HasDefaultValue



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


                Note, there is also HasDefaultValueSql for NULL case:



                        .HasDefaultValueSql("NULL");


                And you can also use the Migrations Up and Down methods, you can alter the defaultValue or defaultValueSql but you may need to drop Indexes first. Here's an example:



                public partial class RemovingDefaultToZeroPlantIdManualChange : Migration
                {
                protected override void Up(MigrationBuilder migrationBuilder)
                {
                migrationBuilder.DropIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME"
                );

                migrationBuilder.AlterColumn<int>(
                name: "COLUMN_NAME",
                table: "TABLE_NAME",
                nullable: true,
                //note here, in the Up method, I'm specifying a new defaultValue:
                defaultValueSql: "NULL",
                oldClrType: typeof(int));

                migrationBuilder.CreateIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME",
                column: "COLUMN_NAME"
                );
                }

                protected override void Down(MigrationBuilder migrationBuilder)
                {
                migrationBuilder.DropIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME"
                );

                migrationBuilder.AlterColumn<int>(
                name: "COLUMN_NAME",
                table: "TABLE_NAME",
                nullable: true,
                //note here, in the Down method, I'll restore to the old defaultValue:
                defaultValueSql: "0",
                oldClrType: typeof(int));

                migrationBuilder.CreateIndex(
                name: "IX_TABLE_NAME_COLUMN_NAME",
                table: "TABLE_NAME",
                column: "COLUMN_NAME"
                );


                }
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 18 at 20:13

























                answered Jun 1 '17 at 1:40









                The Red PeaThe Red Pea

                5,54843978




                5,54843978






























                    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%2f27038524%2fsql-column-default-value-with-entity-framework%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

                    Liquibase includeAll doesn't find base path

                    How to use setInterval in EJS file?

                    Petrus Granier-Deferre