ECC-Dan ECC-Dan - 1 year ago 206
C# Question

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

In a legacy app, most string properties can't be null and need to have a default value of string.empty.

I know it's possible to do this with migrations, but I'm looking for a way to do this using the fluent configuration interface:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
modelBuilder.Properties<string>().Configure(c =>

if (!c.ClrPropertyInfo.IsDefined(typeof (NullableAttribute), false))
// I want to set a default value (string.empty) here.

Is there any way to do this or I'm doomed to initialize all strings in the entity constructors?

Answer Source

Now the answer is Yes:

AddColumn("[table name]", "[column name]", c => c.Boolean(nullable: false, defaultValue: false));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download