ArMaN
ArMaN

Reputation: 2407

EntityFramework naming conventions for DDD ValueObjects

I use Domain Driven Design Pattern in my project. I have some ValueObjects like PersianDate that has a long type property. the name of ValueObject property in database be CreatedOn_PersianDate but I want its name be CreatedOn. I can change this property directly but how can i do it by conventions? (FixOValueObjectAttributeConvention)

public class PersianDate : ValueObject<PersianDate>
{
    public long Value {get; set;}
}

public class Account : Entity
{
    public int Id {get; set;}
    public PersianDate CreatedOn {get; set;}
}

public class TestContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(new FixObjectValueAttributeConvention());
        base.OnModelCreating(modelBuilder);
    }
}

Upvotes: 0

Views: 1387

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109205

You probably noticed that EF's naming convention for properties in complex types is

Property name + "_" + Property name in complex type

So by default, CreatedOn will be mapped as CreatedOn_Value. (As far as I can see, not the name CreatedOn_PersianDate that you mention, but it doesn't really matter for what follows).

You can create a custom code-first convention to modify this. I show you a convention that removes this "_Value" suffix for each property of type long (bigint):

class PersionDateNamingConvention : IStoreModelConvention<EdmProperty>
{
    public void Apply(EdmProperty property, DbModel model)
    {
        if (property.TypeName == "bigint" && property.Name.EndsWith("_Value"))
        {
            property.Name = property.Name.Replace("_Value", string.Empty);
        }
    }
}

Of course you can fine-tune the conditions when this convention is applied as needed.

You have to add this convention to the model builder (in OnModelCreating) to make it effective:

modelBuilder.Conventions.Add(new PersionDateNamingConvention());

Upvotes: 1

wajiro_91
wajiro_91

Reputation: 170

You can do so using DataAnnotations

Column attribute can be applied to properties of a class. Default Code First convention creates a column name same as the property name. Column attribute overrides this default convention. EF Code-First will create a column with a specified name in Column attribute for a given property.

So your models would be:

public class Account : Entity
{
    public int Id {get; set;}

    [Column("CreatedOn")]
    public PersianDate CreatedOn {get; set;}
}

Upvotes: 0

Related Questions