投影,压扁结构

时间:2012-03-23 10:22:45

标签: nhibernate fluent-nhibernate nhibernate-projections

我正在尝试使用这两个类进行投影:

public class SomeClass
{
    public virtual int Id { get; private set; }
    public virtual string Name { get; set; }
    public virtual IList<Language> Languages { get; set; }
}

public class Language
{
     public virtual string Code { get; set; }
}

映射看起来像这样:

public class SomeClassMapping : ClassMap<SomeClass>
{
    public SomeClassMapping()
    {
        Id(x => x.Id).GeneratedBy.Identity();

        Map(x => x.Name)
            .Length(255)
            .Not.Nullable();

        HasMany(x => x.Languages)
            .KeyColumn("SomeClassId")
            .Table("SomeClassLanguages")
            .Component(x => x.Map(y => y.Code))
            .Cascade.All();
    }    
}

public class LanguageMapping : ComponentMap<Language>
{
    public LanguageMapping()
    {
         Map(x => x.Code);
    }
}

这是应该保存结果的类:

public class SomeClassListItem
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Languages { get; set; }
}

从概念上讲,我想要做的是将语言代码变成以逗号分隔的列表,它在下面的代码中表示:

var items = (from s in _session.Query<SomeClass>()
         orderby s.Name
         select new SomeClassListItem
        {
            Id = s.Id,
            Name = s.Name,
            Languages = s.Languages.Select(x => x.Code).Aggregate((current, language) => current + (language + ", "))
        }).ToList();

有关如何使用LINQ,HQL,ICriteria或其他方式实现此目的的任何建议?

1 个答案:

答案 0 :(得分:1)

我认为你的概念代码应该可以解决问题。您唯一想做的就是急切地获取您的语言集合,以避免2次服务器往返。

var items = _session.Query<SomeClass>().Fetch(s => s.Languages)
                .OrderBy(s => s.Name)
                .Select(s => new SomeClassListItem
                 {
                      Id = s.Id,
                      Name = s.Name,
                      Languages = s.Languages.Select(x => x.Code).Aggregate((current, language) => current + (language + ", "))
                 }).ToList();