SQL column default value with Entity Framework

前端 未结 4 926
失恋的感觉
失恋的感觉 2020-12-17 10:09

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()\"

4条回答
  •  粉色の甜心
    2020-12-17 10:46

    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

提交回复
热议问题