How to implement Entity Framework Code First join

做~自己de王妃 提交于 2019-12-10 11:46:46

问题


I'm starting to use Entity Framework Code First.

Suppose to have such POCO's (ultimately simplified):

public class BortStructure
{
   public Guid Id { get; set; }
   public String Name { get; set; }
}

public class Slot
{
   public Guid Id { get; set; }
   public String Name { get; set; }
   public BortStructure { get; set; }
}

public class SystemType
{
   public Guid Id { get; set; }
   public String Name {get; set; }
}

public class SlotSystemType
{
   public Guid Id { get; set; }
   public Slot Slot { get; set; }
   public SystemType SystemType {get; set; }
}

and a context

public MyContext : DbContext
{
   public DbSet<BortStructure> BortStructures { get; set; }
   public DbSet<Slot> Slots{ get; set; }
   public DbSet<SystemType> SystemTypes { get; set; }
   public DbSet<SlotSystemType> SlotSystemTypes { get; set; }
}

I have a task to get BortStructure by Id with list of attached Slots, each one with list of systemTypes attached.

Using SQL allowed me to do that with some JOIN's:

SELECT BortStructures.Id, BortStructures.Name, Slots.Id, 
Slots.Name, SystemType.Id, SystemType.Name FROM
((BortStructures LEFT JOIN Slots ON BortStructures.Id = Slots.BortStructureId)
LEFT JOIN SlotSystemTypes ON SlotSystemTypes.SlotId = Slots.Id)
LEFT JOIN SystemTypes ON SystemTypes.Id = SlotSystemTypes.SystemTypeId
WHERE BortStructures.Id='XXXXXX' ORDER BY Slots.Id, SystemType.Id

But with Entity Framework Code First I don't have any idea howto do that.

If I use

var slotSystemTypes = from sl in MyContext.SlotSystemTypes
where sl.Slot.BortStructure.Id = XXXXXX
orderby sl.Slot.Id, sl.SystemType.Id
select sl;

i, of course, will receive nothing if BortStructure consists of no Slots/Slots without any SystemTypes attached.

Instead of getting BortStructure with empty list of Slots/with Slots, each one with empty list of SystemTypes attached as I expect to get.

Is there any way to archive that with single LINQ query for my database configuration?


回答1:


You can use join operator example:

string[] categories = new string[]{  
    "Beverages",   
    "Condiments",   
    "Vegetables",   
    "Dairy Products",   
    "Seafood" };  

List<Product> products = GetProductList(); 

var q = 
    from c in categories 
    join p in products on c equals p.Category 
    select new { Category = c, p.ProductName }; 

foreach (var v in q) 
{ 
    Console.WriteLine(v.ProductName + ": " + v.Category);  
} 

more samples in: http://code.msdn.microsoft.com/LINQ-Join-Operators-dabef4e9



来源:https://stackoverflow.com/questions/17107194/how-to-implement-entity-framework-code-first-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!