我们的目标是使用 Entity Framework Core 和 .Include(...)扩展方法返回具有子级的对象集合,其中一些子级将为空。
我们有一个表的项目与C#模型项目和表位置用C#模型位置。
每个项目都有一个或零个Location对象,对象如下所示:
public class Project
{
public string LocationId { get; set; }
public Location Location { get; set; }
}
public class Location
{
public string LocationId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
数据库设置如下所示:
modelBuilder.Entity<Location>(entity =>
{
entity.HasKey(location => location.LocationId);
entity.ToTable("Locations");
});
modelBuilder.Entity<Project>(entity =>
{
entity.HasOne(project => project.Location).WithMany()
.HasForeignKey(x => x.LocationId);
entity.ToTable("Projects");
});
Run Code Online (Sandbox Code Playgroud)
我们创建的查询是:
var projects = dbContext.Projects.Include(x => x.Location);
Run Code Online (Sandbox Code Playgroud)
当我们期望 …