我的所有实体和值对象都实现了标记接口IEntity
和IValueObject
。我把它们设置为像这样的组件:
public override bool IsComponent(Type type)
{
return typeof(IValueObject).IsAssignableFrom(type);
}
public override bool ShouldMap(Type type)
{
return typeof(IEntity).IsAssignableFrom(type) || typeof(IValueObject).IsAssignableFrom(type);
}
不幸的是,这似乎不允许将具有值对象集合的实体自动化为组件集合。例如:
public class MyEntity : IEntity
{
public IList<MyValueObject> Objects { get; set; }
}
public class MyValueObject : IValueObject
{
public string Name { get; set; }
public string Value { get; set; }
}
是否有任何方法可以定义约定,以便IEntity
具有实现IList
的类型的IValueObject
时,它就像我指定的一样进行映射: / p>
HasMany(x => x.Objects)
.Component(x => {
x.Map(m => m.Name);
x.Map(m => m.Value);
});
我不想做的是必须为每个类手动执行这些覆盖,并一次又一次地写出值对象的每个属性。
答案 0 :(得分:1)
用以下内容覆盖ShouldMap()方法:
return base.ShouldMap(member) && IsCollectionOfComponents(member)
将您的逻辑添加到:
public void Map(ClassMappingBase classMap, Member member)
{ ... }
用新的步骤替换默认步骤:
public class MyMappingConfiguration : DefaultAutomappingConfiguration
{
public override IEnumerable<IAutomappingStep> GetMappingSteps(AutoMapper mapper, IConventionFinder conventionFinder)
{
var steps = base.GetMappingSteps(mapper, conventionFinder);
var finalSteps = steps.Where(c => c.GetType() != typeof(FluentNHibernate.Automapping.Steps.HasManyToManyStep)).ToList();
var idx = finalSteps.IndexOf(steps.Where(c => c.GetType() == typeof(PropertyStep)).First());
finalSteps.Insert(idx + 1, new MyCustomHasManyStep(this));
return finalSteps;
}
}
注意:您还可以获取HasManyStep.cs的原始源代码并将其复制到您的项目中以介绍您的自定义逻辑。