简体   繁体   English

NHibernate中的QueryOver,子节点为nullable

[英]QueryOver in NHibernate with children nullable

I have two entity (shop and city), and I need to fill a DTO with some values of both entity: 我有两个实体(商店和城市),我需要用两个实体的一些值填充DTO:

The Shop entity: 商店实体:

public class Shop
{
    public virtual int Id {get;set;}
    public virtual string Name {get;set;}
    public virtual string Address {get;set;}
    public virtual int CityId {get;set;}
    public virtual City City {get;set;}
}

The City entity: 城市实体:

public class City
{
    public virtual int Id {get;set;}
    public virtual string NameES {get;set;}
    public virtual string NameEN {get;set;}
    public virtual string NameIT {get;set;}
}

The DTO class: DTO课程:

public class MyDTO
{
    public virtual int Id {get;set;}
    public virtual string Name {get;set;}
    public virtual string CityName {get;set;}
}

I wonder if is any way to do the next SQL query with QueryOver (notice that the City child from shop can be null ): 我想知道是否有任何方法可以使用QueryOver进行下一个SQL查询(请注意,来自商店的City子项可以为null ):

Sesion.CreateSQLQuery("SELECT s.id as Id, s.name as Name, IF(ISNULL(c.NameES),'---', c.NameES) as CityName from shop as s left join city c on c.Id = s.cityId").SetResultTransformer(Transformers.AliasToBean(typeof(MyDTO)))
                    .List<MyDTO>())

Solution could be like this: 解决方案可能是这样的:

// these will server as fully-type representatives, and aliases
Shop shop = null;
City city = null;
MyDTO dto = null;

// shop query
var query = session.QueryOver<Shop>(() => shop);
// if needed a reference to criteria of the city
var cityPart = query.JoinQueryOver(() => shop.City // reference
    , () => city // alias
    , JoinType.LeftOuterJoin); // left join

// SELECT Clause
query.SelectList(list => list
    .Select(() => shop.Id)
        .WithAlias(() => dto.Id)
    .Select(() => shop.Name)
        .WithAlias(() => dto.Name)

    // Conditional here
    .Select(Projections.Conditional(
                Restrictions.Where(() => city.NameES== null),
                Projections.Constant("---", NHibernateUtil.String),
                Projections.Property(() => city.NameES)
        ))
        .WithAlias(() => dto.NameEs)
    );

var result = query
    .TransformUsing(Transformers.AliasToBean<MyDTO>())
    .List<MyDTO>();

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

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