在编辑我的问题之前,我很抱歉我的英语很差。
我有两个班级:
public class News
{
public virtua int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Content { get; set; }
public virtual LearningCenter LearningCenter { get; set; }
}
public class LearningCenter
{
public virtua int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Address { get; set; }
public virtual string ZipCode { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual string Mail { get; set; }
public virtual string DDECode { get; set; }
}
我使用以下主要代码获取新闻列表:
var query = Session
.QueryOver<News>()
.JoinAlias(x => x.Language, () => language, JoinType.LeftOuterJoin)
.JoinAlias(x => x.LearningCenter, () => learningCenter, JoinType.LeftOuterJoin)
.List<News>();
上面的代码从NHibernate转换为单个sql查询,看起来像“SELECT ... FROM News LEFT JOIN LearningCenter WHERE ...”
工作正常。但我想选择一组字段,所以我做了类似......(注意新闻和newsDTO对象有相同的类型)
News news = null;
LearningCenter learningCenter = null;
Language language = null;
News newsDTO = null;
var query = Session
.QueryOver(() => news)
.JoinAlias(() => news.LearningCenter, () => learningCenter, JoinType.LeftOuterJoin)
.JoinAlias(() => news.Language, () => language, JoinType.LeftOuterJoin)
.SelectList(l => l
.Select(x => x.Id).WithAlias(() => newsDTO.Id)
.Select(x => x.LearningCenter).WithAlias(() => newsDTO.LearningCenter))
.TransformUsing(Transformers.AliasToBean<News>())
.List<News>();
但问题是NHibernate将上面的代码翻译成类似于......的n + 1查询
“SELECT ... FROM News LEFT JOIN LearningCenter WHERE ...”
“SELECT ... FROM LearningCenter WHERE CenterId = 388”
“SELECT ... FROM LearningCenter WHERE CenterId = 389”
...
你知道我怎样才能让NHibernate将代码翻译成单个查询?
感谢!!!
答案 0 :(得分:1)
一般来说,有两种方法。
1)我们必须使用Projections,并预测要明确选择的所有属性。然后我们必须使用一些更深层次的转换Deep transformer here
2)我们可以使用批量提取,这将在几个批次中加载所有相关关系。这将导致1 + 2(4)个查询,在分离的(少数)查询中加载所有关系
有关投影的更多详情:
有关批量提取的更多详细信息,请查看: