我有文章和图片。
图像是值对象,文章是实体。图像被映射为组件,例如
public class ImageMap
{
public static Action<IComponentMapper<Image>> Mapping()
{
return c =>
{
c.Property(p => p.AltText);
c.Property(p => p.Name, m =>
{
m.Length(255);
});
c.Property(p => p.Path, m =>
{
m.Length(255);
});
c.Property(p => p.Height);
c.Property(p => p.Width);
c.Parent(x => x.Article, p => p.Access(Accessor.ReadOnly));
};
}
}
我不知道如何通过代码方法映射 nhibernate 映射中的组件列表 在其他只有一个对象而不是集合的组件上,我会使用这个
ArticleMap
Component(c => c.Address, AddressMap.Mapping());
如何映射组件(图像)集合?
Article.cs
public virtual IList<Image> Images {get; set;}
最佳答案
我们需要的是7.2. Collections of dependent objects 。而原理和5.1.13. <component>
的情况几乎是一样的。 ,本例中的元素名称为 <composite-element>
。 事实上,按代码映射有点令人困惑,我们需要 IComponentElementMapper<>
所以,这就是我们的映射方法
public class ImageMap
{
// the <composite-element> as IComponentElement<>
// will replace the above mapper
// public static Action<IComponentMapper<Image>> Mapping()
public static Action<IComponentElementMapper<Image>> Mapping()
{
return c =>
{
c.Property(p => p.AltText);
c.Property(p => p.Name, m =>
{
m.Length(255);
});
c.Property(p => p.Path, m =>
{
m.Length(255);
});
c.Property(p => p.Height);
c.Property(p => p.Width);
c.Parent(x => x.Article, p => p.Access(Accessor.ReadOnly));
};
}
}
现在我们将通过它,正如 Adam Bar 在此处记录的那样 Mapping-by-Code - Set and Bag ,进入映射
// mapping for property:
// public virtual IList<Image> Images {get; set;}
Bag(x => x.Images // reference
, b => { } // bag properties mapper
, v => v.Component(ImageMap.Mapping()) // here we pass the <composite-element>
);
XML 结果将符合预期:
<bag name="Images" ... >
<key column="ArticleId" ... />
<composite-element class="Occupation">
<parent name="Article" access="readonly" />
<property name="AltText" />
<property name="Name" length="255" />
...
</composite-element>
</bag>
关于c# - 如何映射组件集合(值对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23456139/