使用Linq lambda,使用WHERE condision为右表值加入两个tabales并获取左表中的所有值。

问题描述:

我有两个表Entity和EntityPoints



实体表

I have two tables Entity and EntityPoints

Entity table

EntityId | Name
   1     | E1
   2     | E2
   3     | E3





EntityPoints表



EntityPoints Table

EntityId | QId |Points

1        | 1   |100
1        | 2   |200
2        | 2   |350





我的预期输出是:



my expected output is:

Name | EntityId |QId  | Points
E1   |   1      | 2   | 200
E2   |   2      | 2   | 350
E3   |   3      |null | null









我的问题是使用这两个表怎么弄实体表中的所有名称使用EntityPoints的条件表QId ...

我尝试使用以下代码,但它不包含所有实体名称表。我怎么能这样做?









my problem is using this two tables how to get all Names in Entity table using where condition for EntityPoints Table QId ...
I try with following code but it not contain all Names of Entity table.How can I do it ?


using (var db = new EntityContext())
{
    var PGEpoint = db.EntityPoints 
        .Join(db.Entity , p => p.EntityId , q => q.EntityId , (p, q) => new { p, q })
        .Where(w => w.p.QId == 2)
        .Select(m => new TestModel
        {
            pointGEID = m.q.EntityId ,
            PointGE_name = m.q.Name,
            Points = m.p.Points

        }).ToList();
    return PGEpoint;
}

这样的事情应该有效:

Something like this should work:
using (var db = new EntityContext())
{
    return db.Entity.GroupJoin(
        db.EntityPoints.Where(p => p.QId == 2),
        entity => entity.EntityId,
        point => point.EntityId,
        (entity, points) => new 
        { 
            entity, 
            point = points.FirstOrDefault() 
        })
        .Select(m => new TestModel
        {
            pointGEID = m.entity.EntityId,
            PointGE_name = m.entity.Name,
            Points = (m.point == null) ? default(int?) : m.point.Points
        })
        .ToList();
}



Queryable.GroupJoin方法(MSDN) [ ^ ]

如何:执行左外连接(C#编程指南) [ ^ ]