简体   繁体   中英

Including “child tables” when trying to output an Object that contains Lists of Lists

(I am Using Entity Framework and a Code First approach with a LocalDB. I followed the tutorial to get to this point: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model )

I have 3 classes "FleetModel", "ShipModel" and "SailorModel". FleetModel has a List Ships, ShipModel in turn has a List Sailors. And just to make things more interesting SailorModel has an array of strings string[] Operations.

When I create a new FleetModel object, I can see that new tables are created in the Fleet.mdf, with reference IDs, etc. But when I return one such object, only information from the "top level" (= FleetModel) is returned.

I found out that I could use .Include to include (duh) the first "sublevel" like this:

FleetModel output = db.Fleet.Include(x => x.Ships).FirstOrDefault(x => x.Id == id);

But I don't understand the whole construct good enough to include the lower level objects/models. I tried things like:

FleetModel output = db.Fleet.Include(x => x.Ships).Include(x.Sailors).FirstOrDefault(x => x.Id == id);

and

FleetModel output = db.Fleet.Include(x => x.Ships.Sailors).FirstOrDefault(x => x.Id == id);

But it doesn't work, because "Sailors" is unknown to the FleetModel. The output string looks like this:

{"Id":1,"Title":"1st Atlantik Fleet","XCoords":"10","YCoords":"5","Ships":[{"Id":1,"Name":"Alpha","Type":"Carrier","Sailors":null}]}

Another problem is, that it only returns the first Ship, not all of them - should be 2 in this example, each with 3 sailors (a little under-staffed, but hey, we got drones now)

Can anyone point me in the right direction, and maybe tell me where I "don't get" how this system works?

The goal is to input the Id of a Fleet and have it return a JSON string including ALL ships in the fleet and ALL sailors on ALL those ships. (at least I can do the conversion to JSON...).

Thanks for your time!

您可以这样做:

db.Fleet.Include(x => x.Ships).Include(x => x.Ships.Select(y => y.Sailors));

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