entity framework,代码优先。 调用时不会填充子对象

我首先要掌握EF代码。 当我在代码中调用它时,我的域模型设计似乎不支持对象的自动“填充”子项。

模型:

public class Car { [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required,MaxLength(10)] public string Registration { get; set; } [MaxLength(30)] public string Make { get; set; } [MaxLength(45)] public string Model { get; set; } [Required] public Coordinates Coordinates { get; set; } [Required] public Client Client { get; set; } } public class Coordinates { [Key, ForeignKey("Car")] public int Id { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } [Required] public Car Car { get; set; } } 

例如,我只是致电:

 public List Get() { var cars = _context.Cars.ToList(); return cars; } 

我的对象包含数据库中的所有Cars ,但不包括Coordinates 。 数据库种子正确地创建了数据,但我不能让EF自动引用CoordinatesClient 。 但我怀疑一旦我们解决了一个,它就会解决另一个问题。

我做错了什么,我误解了怎么做?

你有两个选择:

  • 通过告诉EF 包含()它们来急切地加载相关实体。 例如,您可以加载Cars包括他们的CoordinatesClients如下所示:

     public List Get() { var cars = _context.Cars .Include(car => car.Coordinates) .Include(car => car.Client) .ToList(); return cars; } 
  • 通过声明virtual导航属性来延迟加载相关实体,从而告知EF在首次访问时加载它们。 确保您的上下文没有禁用的延迟加载,如下所示:

    this.Configuration.LazyLoadingEnabled = false;

一个简短的例子如下所示:

 public class Car { // ... the other properties like in your class definition above public virtual Coordinates Coordinates { get; set;} } public void Get() { var cars = _context.Cars.ToList(); var coordinates = cars.First().Coordinates; // EF loads the Coordinates of the first car NOW! } 
  • 将相关实体明确加载到上下文中。 然后,上下文将为您填充导航属性。 看起来像这样:

     public List Get() { // get all cars var cars = _context.Cars.ToList(); // get all coordinates: the context will populate the Coordinates // property on the cars loaded above var coordinates = _context.Coordinates.ToList(); return cars; } 

您没有Coordinates的原因是因为它未包含在查询中。 有多种方法可以在结果中包含它:

  1. _context.Cars.Include(car => car.Coordinates).ToList(); —它将在一个查询中获取带坐标的汽车
  2. 如果您不需要所有汽车的Coordinates ,您可以执行以下操作:将Coordinates属性设置为虚拟,然后当您获得汽车时,如果需要,您可以仅为其中的子集获取Coordinates ,并且单独的调用将是为每个属性“get”访问数据库。 您还将在调试器中看到EF为您创建了动态类,因此您必须将其设置为virtual
    另请参阅此答案以获取更多详细信息。