c# - 如何映射组件集合(值对象)

标签 c# .net nhibernate

我有文章和图片。

图像是值对象,文章是实体。图像被映射为组件,例如

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/

相关文章:

c# - 存储过程看不到在同一连接中创建的临时表

c# - .Net 桌面应用程序和 Web 应用程序之间的技术区别是什么?

c# - 如何在 C# 中使用 LdapConnection 对象在 LDAP 中搜索用户?

c# - 将 TextBox 的文本绑定(bind)到 list<T> 值的总和

c# - WebBrowser 控件不呈现某些页面

c# - 是否可以在 NHibnernate IQueryable 中按类类型排序

c# - UPS WSDL/C# 示例编译错误

c# - 事件目录是否防止不在域中的客户端进行修改?

c# - NHibernate 多事件监听器

c# - 如何为 NHibernate for MySQL MD5 设置标准?