6

我所有的实体和值对象都实现标记接口IEntityIValueObject。我已经设定好之后,被视为组件,像这样:如何使用Fluent NHibernate自动映射组件集合?

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); 
} 

不幸的是,这似乎并没有允许拥有价值对象的集合被automapped作为组件的集合实体。例如:

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具有实现IValueObject的类型的IList,它将映射我仿佛指定:

HasMany(x => x.Objects) 
    .Component(x => { 
     x.Map(m => m.Name); 
     x.Map(m => m.Value); 
    }); 

我不想做的是必须为每个类手动执行这些覆盖,并一次又一次地写出value对象的每个属性。

回答

0
  1. 创建一个继承自HasManyStep(FluentNHibernate.Automapping.Steps)的新类。
  2. 覆盖的ShouldMap()方法是这样的:

    return base.ShouldMap(member) && IsCollectionOfComponents(member) 
    
  3. 你的逻辑添加到:

    public void Map(ClassMappingBase classMap, Member member) 
    { ... } 
    
  4. 与您更换新的默认步:

    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的原始源代码并将其复制到您的项目中以引入您的自定义逻辑。

相关问题