0

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

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 或其他方式完成此任务的任何建议?

4

1 回答 1

1

我认为您的概念代码应该可以解决问题。您唯一想做的就是急切地获取您的 Languages 集合以避免 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();
于 2012-03-23T15:18:29.227 回答