实体框架,代码优先.调用时不会填充子对象

Dam*_*amo 9 c# entity-framework ef-code-first

我首先要掌握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; }
}
Run Code Online (Sandbox Code Playgroud)

例如,我只是致电:

public List<Car> Get()
{            
    var cars = _context.Cars.ToList();
    return cars;
}
Run Code Online (Sandbox Code Playgroud)

我的对象包含Cars数据库中的所有内容,但不包含Coordinates.数据库种子正确地创建了数据,但我不能让EF自动引用Coordinates,或者Client就此而言.但我怀疑一旦我们解决了一个问题,它就会解决另一个问题.

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

and*_*dyp 28

你有两个选择:

  • 通过告诉EF 包含()它们来急切地加载相关实体.例如,你可以加载Cars,包括他们CoordinatesClients这样的:

    public List<Car> Get()
    {            
        var cars = _context.Cars
            .Include(car => car.Coordinates)
            .Include(car => car.Client)
            .ToList();
        return cars;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 通过声明导航属性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!
}
Run Code Online (Sandbox Code Playgroud)
  • 将相关实体明确加载到上下文中.然后,上下文将为您填充导航属性.看起来像这样:

    public List<Car> 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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 如果在 `.Include(car =&gt; car.Coordinates)` 中找不到 lambda 表达式,请添加 `using System.Data.Entity;` (2认同)