的EntityFramework关系一个多对一(插入帮助这里) - 渴望加载

问题描述:

我有4个车型的EntityFramework关系一个多对一(插入帮助这里) - 渴望加载

  1. 类型A
  2. 的TypeB

厂可以有许多汽车,一辆汽车可以有TypeA和TypeB。这两种类型A和类型B可以使用eager-loading 汽车 即IM存在,所以我的模型看起来像

public class Factory 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int FactoryID {get;set;} 

    public ICollection<Car> Cars {get;set;} 
} 

public class Car 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int CarID {get;set;} 

    public int FactoryID {get;set;} 
    public Factory Factory {get;set;} 

    //The Types 
    public TypeA TypeA {get;set;} 
    public TypeB TypeB {get;set;} 
} 

public class TypeA 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int TypeAID {get;set;} 

    [Key, ForeignKey("Car")] 
    public int CarID {get;set;} 
    public Car Car {get;set;} 
} 

public class TypeB 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int TypeBID {get;set;} 

    [Key, ForeignKey("Car")] 
    public int CarID {get;set;} 
    public Car Car {get;set;} 
} 

这里是我的问题。如何加载两个类型A和类型B到我的工厂对象(用渴望装载)

Factory factory = db.Factory.Where(f => f.FactoryID == 1).Include(f => f.Cars.Select(c => c.TypeA) ... .FirstOrDefault(); 

因为我不能说

Include(f=>f.Cars.Select(...).Select(...)) 
+1

您可以用typeB重复'Include'语句。 – 2014-11-21 09:44:09

刚刚链include声明:

Factory factory = db.Factory.Where(f => f.FactoryID == 1) 
          .Include(f => f.Cars.Select(c => c.TypeA)) 
          .Include(f => f.Cars.Select(c => c.TypeB)) 
          ....; 

顺便说一句: 这可能将是有意义的引入基类TypeATypeB - 甚至只是用一类,因为我没有看到他们两人之间的差异。

+1

两者之间有一个明确的区别,我只是抽象了整个事情:) – VisualBean 2014-11-21 09:47:33

可以拥有多个包含语句。没有必要只有一个。

+0

好吧,那很容易:)谢谢 – VisualBean 2014-11-21 09:49:08