DDD ValueObjects的EntityFramework命名约定 [英] EntityFramework naming conventions for DDD ValueObjects
问题描述
我在项目中使用域驱动设计模式.我有一些 ValueObjects ,例如 PersianDate 具有长型属性.数据库中ValueObject属性的名称为CreatedOn_PersianDate,但我希望其名称为CreatedOn.我可以直接更改此属性,但是如何通过惯例进行更改? (FixOValueObjectAttributeConvention)
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);
}
}
推荐答案
您可能已经注意到EF的复杂类型属性命名约定是
You probably noticed that EF's naming convention for properties in complex types is
Property name + "_" + Property name in complex type
因此,默认情况下,CreatedOn
将映射为CreatedOn_Value
. (据我所知,并不是您提到的名称CreatedOn_PersianDate
,但这对后面的内容并不重要).
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).
您可以创建一个自定义代码优先约定来进行修改.我向您展示了一个约定,该约定删除了long
(bigint)类型的每个属性的"_Value"后缀:
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.
您必须将此约定添加到模型构建器(在OnModelCreating
中)以使其生效:
You have to add this convention to the model builder (in OnModelCreating
) to make it effective:
modelBuilder.Conventions.Add(new PersionDateNamingConvention());
这篇关于DDD ValueObjects的EntityFramework命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!