0

NHibernate 长期以来一直存在问题,我通过非最佳方式/解决方法解决了该问题。

首先,我使用 WCF REST 与我的客户端应用程序进行通信。如您所知,序列化持久化实体并不是最佳实践,而且总是会导致其他问题。因此,我总是使用 NHibernates Transformers 将我的实体映射到 DTO。问题是我有更复杂的实体,使用 Transformer 来转换它们。

如何使用转换器或任何其他休眠功能将子实体映射到子 dto?

注意:我不想使用像Automapper这样的 3rd 方。

这些是我要映射的实体和 DTO。变量名称彼此完全相同。

实体类:

实体类型

public class crmEntityType : EntityModel<crmEntityType>
{
    public crmEntityType()
    {
        Association = new List<crmEntityType>();
        Fields = new List<crmCustomField>();
    }

    public virtual int ID { get; set; }

    public virtual string Title { get; set; }

    public virtual ICollection<crmEntityType> Associations { get; set; }

    public virtual ICollection<crmCustomField> Fields { get; set; }

}

自定义字段

    public class crmCustomField : EntityModel<crmCustomField>
{
    public virtual int ID { get; set; }

    public virtual string Name { get; set; }

    public virtual crmEntityType EntityType { get; set; }
}

DTO's

EntityTypeDTO

[DataContract]
public class EntityTypeDTO
{
    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public string Title { get; set; }

    [DataMember]
    public IList<CustomFieldDTO> Fields { get; set; }

    [DataMember]
    public int[] Associations { get; set; }
}

CustomFieldDTO

[DataContract]
    public class CustomFieldDTO
{
    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int EntityType { get; set; }

    [DataMember]
    public int FieldType { get; set; }

}
4

1 回答 1

1

I found my solution by spending my day and night to work it out. Finally, I've got the best solution I could find. I hope it helps someone in my condition some day.

This linq query works with just one database round-trip. I think it maps the classes in memory.

return (from entityType in Provider.GetSession().Query<crmEntityType>()
                .Fetch(x => x.Association)
                .Fetch(x => x.Fields)
                .AsEnumerable()
    select new EntityTypeDTO()
    {
        ID = entityType.ID,
        Title = entityType.Title,
        Association = entityType.Association.Distinct()
                               .Select(asc => asc.ID).ToArray<int>(),
        Fields = entityType.Fields.Distinct()
                               .Select(fi => new CustomFieldDTO 
                                            { ID = fi.ID, 
                                              Name = fi.Name, 
                                              Value = fi.Value, 
                                              EntityType = fi.EntityType.ID,
                                              Type = fi.Type 
                                            }).ToList()
    }).ToList();
于 2012-12-08T00:33:41.193 回答