Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Code First FluentAPI DefaultValue in EF6.X

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); 
like image 312
Tony Bao Avatar asked Nov 25 '13 17:11

Tony Bao


People also ask

How do you configure a primary key for an entity in Entity Framework fluent API?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

How do I set default value in EDMX?

edmx viewer select an entity -> go the column -> properties -> Default Value. Add the default value for the column in it and that's it.

Does Entity Framework have default value?

The Entity Framework Core Fluent API HasDefaultValue method is used to specify the default value for a database column mapped to a property. The value must be a constant.


2 Answers

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

like image 126
htxryan Avatar answered Sep 22 '22 21:09

htxryan


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

like image 44
NinjaNye Avatar answered Sep 23 '22 21:09

NinjaNye