.Join .Group Lambda多表

时间:2016-03-11 10:39:31

标签: asp.net-mvc entity-framework linq lambda

我需要转换:

SELECT Author.AuthorName, Author.AuthorSurname , Category.CategoryName, COUNT(Record.IdCategory) AS Ilosc  
FROM ((Record
INNER JOIN Author ON Author.Id = Record.IdAuthor)
INNER JOIN Category ON Category.Id = Record.IdCategory)
GROUP BY AuthorName, AuthorSurname, CategoryName
Order by Ilosc ASC

致lambda。 我创建了

public class SortModel
{
    public string Imie { get; set; }
    public string Nazwisko { get; set; }
    public string Kategoria { get; set; }
}

现在我写了这段代码,但我需要添加.groupby

    public List<SortModel> GetAuthorCategories()
    {

        var context = new KolekcjaPlytEntities2();

        List<SortModel> queryAllCustomers = context.Record
            .Join( context.Author, r => r.IdAuthor, a => a.Id, (r, a) => new {r, a})
            .Join(context.Category, c => c.r.IdCategory, cn => cn.Id, (c, cn) => new SortModel()

            {
                Imie = c.a.AuthorName,
                Nazwisko = c.a.AuthorSurname,
                Kategoria = cn.CategoryName,
            })
               .ToList();

        return queryAllCustomers;

    }

感谢。

2 个答案:

答案 0 :(得分:1)

您可以像这样使用LINQ查询表达式。

     List<SortModel> queryAllCustomers = (from r in context.Record
     join a in context.Author on r.IdAuthor equals a.Id
     join c in context.Category on r.IdCategory equals c.Id
     group new {a, c} by new {a.AuthorName, a.AuthorSurname , c.CategoryName} into gruopAC
     let countCategory= gruopAC.Count()
     orderby countCategory
     select new SortModel
     {
        Imie=gruopAC.Key.AuthorName,
        Nazwisko =gruopAC.Key.AuthorSurname ,
        Kategoria =gruopAC.Key.CategoryName,
        Ilosc=countCategory}).ToList()

答案 1 :(得分:0)

假设你有

public class SortModel
{
    public string Imie { get; set; }
    public string Nazwisko { get; set; }
    public string Kategoria { get; set; }
    public int Ilosc { get; set; }
}

您可以尝试以下代码:

public List<SortModel> GetAuthorCategories()
{
    var context = new KolekcjaPlytEntities2();

    List<SortModel> queryAllCustomers = context.Record
        .Join(context.Author, r => r.IdAuthor, a => a.Id, (r, a) => new {r, a})
        .Join(context.Category, ar => ar.r.IdCategory, c => c.Id, (ar, c) => new {
            r = ar.r,
            a = ar.a,
            c = c
        })
        // Here you have a IEnumerable<dynamic> of items { a = Author, c = Category, r = Record }
        // All items with same { a.Id, c.Id } are grouped
        .GroupBy(x => new { x.a.Id, x.c.Id }, (x, items) => new SortModel()
        {
            // First() cannot return null, we have inner join everywhere
            Imie = items.First().a.AuthorName,
            Nazwisko = items.First().a.AuthorSurname,
            Kategoria = items.First().c.CategoryName,
            Ilosc = items.Count()
        })
        .ToList();

    return queryAllCustomers;
}