小编Dav*_*win的帖子

使用 C# EF Core 返回具有空子级的父级。包括

我们的目标是使用 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)

当我们期望 …

c# entity-framework entity-framework-core

3
推荐指数
2
解决办法
2727
查看次数