How to select a column from multiple tables in c#?

Jeune Padawan :

my problem comes from the fact that I'm very new to this. Basically, I'm kind of trying to make a restapi in c# and it's currently connected to a mysql databse on my localhost. I have multiple tables with relations and from one of the tables, I want to list all the records from that table where its relations contain a specific string in their tables.

Let's say I have a Building table which has multiple columns, batteries and elevators. I'd want to list all the buildings where it has either a column, battery or elevator with an 'inactive' status, status being the column name.

My code currently looks as follow, though obviously wrong :

[HttpGet("intervention")]
public List<Buildings> Getintervention(string status)
{
    var myintervention = _context.buildings.Select(e => e.status == "Inactive").From(Batteries).ToList();
    return myintervention;
}

I know for a fact I could do a query like this and it works : var unavailable = _context.elevators.Where(e => e.status != "Active").ToList();

Problem is... I don't know how to do it since my Building table does not have any status column and currently it returns me an error saying that.. it doesn't contain a status column. lol.

If anyone has an idea of how I could do this, let me know!

Thank you :)

Caius Jard :

I'm not clear on whether this is EF or EF core and/or how you load your related data but I would expect it to look like this if the building collection has already eagerly loaded or will implicitly load the batteries / columns / elevators:

context.Buildings.Where(b =>
  b.Batteries.Any(ba => ba.Status == "Inactive) ||
  b.Columns.Any(c => c.Status == "Inactive) ||
  b.Elevators.Any(c => c.Status == "Inactive)
);

If a Building doesn't load these collections / they are loaded explicitly you might need to do something like context.Buildings.Include(b=>b.Batteries).Include(b=>b.Columns)... before your where. You should be mindful that in recent versions of EF core that joins are used rather than running separate queries and multiple includes may cause a Cartesian explosion (a building with 10 batteries, 10 columns and 10 elevators will cause 1000 rows to be generated, and EF will have to pick through the result set to boil it back down to 31 entities)

It may this be more performant to hit your tables individually, collecting buildings or building ids from them:

context.Batteries(b=> b.Status == "Inactive").Select(ba => ba.Building);
context.Batteries(b=> b.Status == "Inactive").Select(ba => ba.BuildingID);

And then later (retrieving buildings via the ids) then reporting on the buildings

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=395250&siteId=1