简体   繁体   English

WebAPI JSON 序列化实体框架

[英]WebAPI JSON Serialize Entity Framework

In my WebAPI, I'm using EF.在我的 WebAPI 中,我使用的是 EF。 I'm currently getting my data out using a LINQ statement.我目前正在使用 LINQ 语句获取我的数据。

My LINQ is:我的 LINQ 是:

var output = _context.CarMakes
.Select(x => new 
{
   id= x.CarId,
   make = x.CarMake,
   year = x.Year,
   status = x.Status 
});

my data is returned as:我的数据返回为:

[
     { 
        "id": 1,
        "make": "Ford",
         "year" : 2020,
        "model" : "Focus"
     },
     {
        "id" : 2,
        "make" :"Ford",
        "year" : 1994,
        "model" : "F-150"
     },
     {
       "id" : 3,
       "make" : "Chevy",
       "year" : 2022,
       "model" : "Silverado"
  
     }
   ]
 

How can I get it returned so it's grouped so I can use it in a TreeView navigation menu such as: What changes should I make to the .NET code?我怎样才能将它返回以便将其分组以便我可以在 TreeView 导航菜单中使用它,例如: 我应该对 .NET 代码进行哪些更改?

   Ford:
      2020
        Focus
       1994
         F-150
   Chevy
       2022
         Silverado
      
       

you need to use group by to get the result needed, here is an example:您需要使用 group by 来获得所需的结果,这是一个示例:

var result = _context.CarMakes.GroupBy(x => x.make)
    .Select(g => new {
        Make = g.Key,
        Models = g.GroupBy(x => x.year)
            .Select(y => new {
                Year = y.Key,
                Name = y.Select(z => z.model)
            })
    });

You have to perform group by on make and year fields and then select all the cars that come under those grouping.您必须按make商和year字段执行分组,然后 select 所有属于这些分组的汽车。 Then in the front end, you can use this returned data to make a nested tree view.然后在前端,你可以使用这个返回的数据来做一个嵌套的树视图。

var output = _context.CarMakes
    .Select(x => new
    {
        id = x.CarId,
        make = x.CarMake,
        year = x.Year,
        status = x.Status
    })
    .GroupBy(x => new { x.make, x.year })
    .Select(g => new
    {
        make = g.Key.make,
        year = g.Key.year,
        cars = g.Select(x => new { id = x.id, status = x.status })
    });

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

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