简体   繁体   中英

How to include optional relations in C# using Code First Entity Framework

Having the DB below I would like to retrieve all bricks in C# and include the Workshops on those BrickBacks that has any.

I managed to retrieve all the Bricks and include the BrickBacks by simply doing

context.Bricks.Include(b=>b.Back).ToList()

But in this case BrickBack is an abstract class which its subclass may contain a Workshop but this is not always the case.

Unfortunately I can't just do

context.Bricks.Include(b=>b.Back).Include(b=>b.Back.Workshop).ToList()

How can this be done?

数据库图

This could work context.Bricks.Include("Back").Include("Workshop").ToList()

WorkShop will be null if Workshop_Id is null in the database.

Not possible. Maybe you can approach it from a different angle:

ConcreteBacks.Include(b => b.WorkShop)
             .Include(b => b.Bricks)
             .AsEnumerable()
             .SelectMany(b => b.Bricks)

This will pull all ConcreteBacks and the included data from the database and then return the Bricks in a flattened list.

The AsEnumerable() is necessary because EF only includes data off the root entities in the result set. Without AsEnumerable() this would be Brick and the ConcreteBacks would be ignored. But now EF only knows about the part before AsEnumerable() , so it includes everything off ConcreteBack .

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