简体   繁体   中英

Select all rows from a model and have a nested json element as the Foreign key to another model with all rows selected

I would like my JSON element returned by my controller to look like this

{           
    "model": "Ford",
    "make": "GT350R",
    "dealerName": "Dallas Ford",
    "location": {
        "dealerName": "Dallas Ford",
        "zip": 05700,
    }
}

I cant seem to get the query right in my controller. I want to select all rows and every element from the Cars Model and where there is a foreign key to the location Table. I then want to embed all the rows that belong to that location element into a sub element. I think i may need to tell my models about the foreign key but because i am using the same attribute name i think Entity Framework 6 does it for me.

This is the code I am trying which will only select all the results from Cars it wont show the location as a nested element.

var query = (from results in db.Cars
             join location in db.Locations on results.DealerName equals location.Dealername
             select results);
return Ok(query.ToList());

This is the json that it shows for each element

{ 
    "model": "Ford",
    "make": "GT350R",
    "dealerName": "Dallas Ford",
}

Here are my models

Car model

//......
[Key]
public string make { get; set; }
public string model { get; set; }
public Location Locations{ get; set; }//added this because someone in comments said to
public string dealerName { get; set; }
//........

Location model

//......
[Key]
public string dealername{ get; set; }
public string Zip { get; set; }
//........

And heres what i think the code should look like but I am not doing it right.

var query = (from results in db.Cars
             join location in db.Locations on results.DealerName equals location.Dealername
             select new {
                 results = results;
                 results.location = location;
             });
return Ok(query.ToList());

Try this

    var query = (from results in db.Cars
                 join location in db.Locations on results.dealerName equals location.dealerName 
                 select new {
                   model = results.model, make = results.make, dealerName = results.dealerName, location = location }     
             );
                return json(query.ToList());

Make your life simpler and use the Entity Framework syntax. Even though you can use LINQ to SQL, it's just so much more verbose and problematic to work with. All you need is:

var query = db.Cars.Where(m => m.Locations.Any()).Include(m => m.Locations);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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