SQL column default value with Entity Framework

.net entity-framework entity-framework-6

Accepted Answer

There is currently no attribute in EF6 that defines database functions used for a certain property default value. On Codeplex, you can cast a vote to get it implemented:

https://entityframework.codeplex.com/workitem/44

Utilizing is the accepted method to implement something like that.Computed buildings withMigrations where the default database function is specified.

In C#, your class might seem as follows:

public class MyEntity
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime Created { get; set; }
}

It is not necessary for the computed property to be nullable.

The default SQL function must then be added manually after running a migration. A migration might resemble:

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

The defaultValueSql function will be shown. The secret to making the calculations work is that.

21
11/20/2014 5:02:49 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow