简体   繁体   English

从二级表(实体框架)获取数据

[英]Getting data from a second level table (entity framework)

Working on MVC 5 application, with EF. 使用EF处理MVC 5应用程序。

I have 3 tables in my database. 我的数据库中有3个表。 For a simple example let me use this.... 作为一个简单的例子,让我用这个...。

  • Cars 汽车
    • Id ID
    • CarName CarName
  • Colors 颜色
    • Id ID
    • ColorName ColorName
  • CarsColors CarsColors
    • CarId CarId
    • ColorId ColorId

Cars and Colors are "master" tables. 汽车和颜色是“主”表。 CarsColors, is a cross-reference table that holds various combinations. CarsColors是包含各种组合的交叉引用表。

Objective: Create a view that shows a table. 目标:创建一个显示表格的视图。 For each row it will display car details. 每行将显示汽车详细信息。 There will be a column for "Colors". 将有一个“颜色”列。 In the "Colors" column there will be a comma-delineated list of colors used by that car. 在“颜色”列中,将有该车使用的颜色的逗号分隔列表。 (This is the core of my problem.) So, for example.... (这是我问题的核心。)因此,例如...

 <table> <th>Cars</th> <th>Colors</th> <tr> <td>Kia Sportage</td> <td>Red, Blue, Green</td> </tr> <tr> <td>Toyota Camery</td> <td>Green, Black</td> </tr> <tr> <td>Honda Odyssey</td> <td>(nothing)</td> </tr> </table> 

I'm not sure exactly how to do this. 我不确定该怎么做。 I know with my Cars select that I can use an .Include() to include CarsColors. 我知道我的Cars选择项可以使用.Include()包含CarsColors。 But, how would I go "UP" one level to get the Cars.ColorName? 但是,我将如何向上“一级”获得Cars.ColorName? I need to cycle thru CarsColors in order to populate the last column of each row, but use the Colors table for the actual color name. 我需要通过CarsColors循环以填充每行的最后一列,但是使用Colors表作为实际的颜色名称。

Thanks 谢谢

You could use a navigation property to get the color name: 您可以使用导航属性获取颜色名称:

public partial class CarsColors
{
    public int CarId { get; set; }
    public int ColorId { get; set; }

    public virtual Car Car { get; set; }
    public virtual Color Color { get; set; }
}

So having an object of type CarsColors you could read the Color name as below: 因此,拥有一个类型为CarsColors的对象,您可以读取Color名称,如下所示:

obj.Color.ColorName

Something like the folowing does what you are looking for: 像下面这样的东西可以满足您的需求:

var cars = dbContext.Cars
                    .Include(car=>car.CarsColors)
                    .GroupBy(car=>car.CarName)
                    .Select(gr=> new 
                    {
                        CarName = gr.Key,
                        Colors = string.Join(",", gr.Select(car=>car.CarsColors.Color.ColorName))
                    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM