nhibernate:从子查询中生成父项

时间:2012-10-10 09:29:58

标签: nhibernate queryover nhibernate-projections

我有以下实体

public class ArticleCategory
{
  public int Id {get; set;}
  public string Name {get; set;}
  public IList<Article> Articles {get; set;}
}

public class Article
{
  public int Id {get; set;}
  public string Name {get; set;}
  public ArticleCategory Category {get; set;}
}

public class JobArticles
{
  public int Id {get; set;}
  public Job Job {get; set;}
  public decimal Price {get; set;}
  public Article Article {get; set;}
}

如您所见,文章对于分配的哪个JobArticle一无所知(这是无关紧要的)

所以我需要做的是以下内容。 获取Job X存在Job X的每个ArticleCategory。

最简单的方法是将JobArticle列表添加到文章实体。但我不确定这是不是最好的方式。

所以我尝试了相反的方式(从JobArticle到ArticleCategory)。像这样的东西

IQueryOver<JobArticle, JobArticle> q = DataSession.Current.QueryOver<JobArticle>();

        Article ArticleAlias = null;
        ArticleCategory ArticleCategoryAlias = null;

        q.JoinAlias(x => x.Article, () => ArticleAlias);
        q.JoinAlias(x => ArticleAlias.Category, () => ArticleCategoryAlias);
        q.Where(x => x.Job.Id == jobId);
        q.SelectList(list => list
            .Select(x => ArticleCategoryAlias))

由于.Select(x => ArticleCategoryAlias)

导致NULL引用异常

我不确定该怎么做,希望你能帮忙

1 个答案:

答案 0 :(得分:0)

Article ArticleAlias = null;
ArticleCategory ArticleCategoryAlias = null;

var categories = DataSession.Current.QueryOver<ArticleCategory>()
    .WithSubquery.WhereProperty(x => x.Id).In(QueryOver.Of<JobArticle>()
        .JoinAlias(x => x.Article, () => ArticleAlias);
        .JoinAlias(x => ArticleAlias.Category, () => ArticleCategoryAlias);
        .Where(x => x.Job.Id == jobId);
        .Select(() => ArticleCategoryAlias.Id))
    .List();