如何连接两个表并使用Entity Framework从记录中获取计数记录

时间:2016-05-24 03:29:54

标签: asp.net-mvc entity-framework linq-to-entities

我想使用Entity Framework连接两个表并获得输出结果

table 1                          table2

idst      name                   idtable2        idst         
-----------------                ---------------------
1         ali                       1              1
2         reza                      2              1
3         amir                      3              2 
4         obama                     4              2

所需的查询结果:

row       name      count 
-------------------------
1         ali         2
2        reza         2
3         amir        0

我写了这段代码:

var query = _Colorproductt.OrderBy(x => x.Productid)
                          .Skip((page - 1) * count)
                          .Take(count)
                          .Select(a => new Colormodel
                                      {
                                         Id = a.Id,
                                         Countcolorsixe = Convert.ToInt16(_sizeproductt.Where(x => x.Id == a.Id).Count().ToString()),
                                         Productid = a.Productid,
                                        PrincipleImagePath = a.PrincipleImagePath
                                      });

var q = _Colorproductt.Join(_sizeproductt, 
                            c => c.Id, p => p.color_id, 
                            (c, p) => new { ID_ProductId = c.Productid, PrincipleImagePath = c.PrincipleImagePath, Id = c.Id,  Product = p })
                      .ToList();

2 个答案:

答案 0 :(得分:0)

我在LinqPad中尝试这个,它确实检索了你想要的数据。我不认为这是一个好的答案,希望有人可以改善这一点。

void Main()
{
    var table1 = new List<class1>(){
        new class1{ idst=1 , name="ali" },
        new class1{ idst=2, name="reza" },
        new class1{ idst=3 , name="amir" },
        new class1{ idst=4 , name="obama" },
    };

    var table2 = new List<class2>(){
        new class2{ idtable2=1, idst=1 },
        new class2{ idtable2=2,  idst=1 },
        new class2{ idtable2=3, idst=2 },
        new class2{ idtable2=4, idst=2 },
    };

   var query = from t1 in table1
               join t2 in table2.GroupBy(x=>x.idst).Select( x=> new {idst = x.FirstOrDefault().idst, count = x.Count()}) 
               on t1.idst equals    t2.idst into g          
               from t3 in g.DefaultIfEmpty()
               select new  {
               t1.name,
               count = g.Sum(x=>x.count)
               };


                query.Dump();
}

class class1{
    public int idst {get;set;}
    public string name {get;set;}
}

class class2{
    public int idtable2 {get;set;}
    public int idst {get;set;}
}

答案 1 :(得分:0)

考虑您的实体名称是ColorProduct和SizeProduct

var query = from p in ColorProduct
            let cc = (
                from s in SizeProduct
                where p.Id == s.ProductId
                select s
                ).Count()
            select new {row = p.Id, name = p.Name, count = cc};