简体   繁体   English

NHibernate DTO映射

[英]NHibernate DTO mapping

  1. Is it OK to create Mappings for DTO objects and then query them instead of domain? 是否可以为DTO对象创建映射,然后查询它们而不是域? If it is not explain why? 如果不解释原因?
  2. What If i need couple of those dtos? 如果我需要几个dtos怎么办?

  • DTos are readonly DTos是只读的
  • ID is autogenerated by NH ID由NH自动生成
  • In future these dtos will have set mappings to linked dtos. 将来这些dtos将设置映射到链接的dtos。
  • I use DTO to reduce query size 我使用DTO来减少查询大小

     <class name="Person" table="`APP_Person`"> <property name="FirstName" type="string" length="512" /> <property name="Age" type="int" /> <property name="SocialNumber" type="int" /> <property name="PassportId" type="int" /> <property name="Salary" type="int" /> </class> <class name="PersonDTO" table="`APP_Person`"> <property name="FirstName" type="string" length="512" /> <property name="Age" type="int" /> </class> 

You don't need to map/persist a DTO object. 您不需要映射/保留DTO对象。 It's normaly to readonly data and send to other layer of your application (web services, views, etc...). 只读数据并发送到应用程序的其他层(Web服务,视图等)是正常的。

You can create a query on the Person entity that returns a PersonDTO list. 您可以在Person实体上创建一个返回PersonDTO列表的查询。 Take a look at SetResultTransformer method. 看看SetResultTransformer方法。 Try somethin like this: 尝试这样的事情:

var query = session.CreateQuery("select p.FirstName, p.Age from Person p order by p.FirstName")
                   .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(PersonDTO)))
                   .List<PersonDTO>();

And your DTO: 而你的DTO:

public class PersonDTO 
{
   public string FirstName { get; set; }
   public int Age { get; set; }
}

The result of the column on the hql query should have the same name of your DTO's properties to NHibernate do the right reflection when construct the DTO and hydrate the object. hql查询中的列的结果应该与DTO的属性具有相同的名称,NHibernate在构造DTO时进行正确的反射并对对象进行水合。

Linq LINQ

You also can use linq to have a DTO (or a list of DTOs) as a result. 您也可以使用linq来获得DTO (或DTO列表)。 For sample: 样品:

var query = Session.Query<Person>().OrderBy(x => x.FirstName)
                   .Select(x = new PersonDTO() { FirstName = x.FirstName, Age = x.Age })
                   .ToList();

Look this article: http://gustavoringel.blogspot.com.br/2009/02/creating-dto-in-nhibernate-hql-using.html 看看这篇文章: http//gustavoringel.blogspot.com.br/2009/02/creating-dto-in-nhibernate-hql-using.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM