问题
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);
}
}
回答1:
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());
回答2:
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;}
}
来源:https://stackoverflow.com/questions/37242530/entityframework-naming-conventions-for-ddd-valueobjects