EF 6 Codefirst -Setting default value for a property defined in base class using fluent API

ef-fluent-api entity-framework entity-framework-6

Question

I have a base class which has audit properties like

public abstract class BaseModel
{
    [Column(Order = 1)] 
    public long Id { get; set; }
    public long CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public long ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
    public bool IsActive { get; set; }
}

All my poco classes derive from this class.

I am trying to set a default value to the IsActive properties. I am not keen on using annotations and hence was wandering if I can work this using fluent API.

I tried this but it does not work. Seems like it creates a new table named BaseModel

modelBuilder.Entity<BaseModel>()
    .Property(p => p.IsActive)
    .HasColumnAnnotation("DefaultValue", true);

Can any one suggest a way here?

1
2
6/19/2015 7:24:34 PM

Popular Answer

There is no way to do this. It can't set default values with Entity Framework. Instead you can use the constructor

public abstract class BaseModel
{
    protected BaseModel()
    {
        IsActive = true;
    }
}
5
6/19/2015 6:50:00 PM


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