使用 linq 显示所有行



假设我有表格

Shape
Id     ShapeName
1      Circle
2      Square
3      Triangle
4      Pentagon
ShapeColour
Id     ShapeId   Colour
1      1         Red
2      1         Yellow
3      2         Green
4      3         Blue
5      3         Orange

在实体框架中,我会有一个形状对象,其中 ShapeColors 列表作为该形状的属性,但我想要的是一个扁平列表,就好像我使用 sql

一样
DesiredObject
ShapeId ShapeColourId ShapeName Colour
1       1             Circle    Red
1       2             Circle    Yellow
2       3             Square    Green
3       4             Triangle  Blue
3       5             Triangle  Orange
4       null          Pentagon  null

希望我的例子足够了。

你可以

做这样的双from;

var query= from s in context.Shapes
           from sc in s.ShapeColours.DefaultIfEmpty()
           select new {ShapeId=s.Id, 
                       ShapeColourId=sc.Id,
                       ShapeName=s.Name, 
                       Colour=sc.Colour
                      };

没有看到你的确切实体,我猜你想要这样的东西

var results = from shape in db.Shapes
              from colour in shape.ShapeColours.DefaultIfEmpty()
              select new
              {
                  shape.ShapeId,
                  colour.ShapeColourId,
                  shape.ShapeName,
                  colour.Colour
              };

使用 EF,可以将导航属性用于通过外键关联的表。 若要执行左联接,只需在导航属性集合上使用 DefaultIfEmpty()

最新更新