使用C#EF Core返回包含零孩子的父母. [英] Return parents with null children using C# EF Core .Include

查看:42
本文介绍了使用C#EF Core返回包含零孩子的父母.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的目标是使用Entity Framework Core和 .Include(...)扩展方法查询数据库,以返回具有子对象的对象的集合,其中一些对象孩子将为空.

Our goal is to query a database, using Entity Framework Core and the .Include(...) extension method to return a collection of objects that have a child, where some of the children will be null.

我们有一个带有C#模型 Project 的表 Projects 和一个带有C#模型 Location 的表 Locations .

We have a table Projects with a C# model Project and a table Locations with a C# model Location.

每个 Project 有一个或零个 Location 对象,这些对象看起来像这样:

Each Project has a one or zero Location objects and the objects look like this:

public class Project
{
     public string LocationId { get; set; }
     public Location Location { get; set; }
}

public class Location
{
     public string LocationId { get; set; }
}

数据库设置如下:

        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");

        });

我们创建的查询是:

var projects = dbContext.Projects.Include(x => x.Location);

当我们期望 LEFT OUTER JOIN

SELECT [project].[LocationId] 
FROM [Projects] AS [project] 
LEFT JOIN [Locations] AS [c] ON [project].[LocationId] = [c].[LocationId]

结果是仅返回具有位置的项目.我们需要所有项目及其位置.

来自此链接我理解 .Include(...)根据外键的可空性决定执行LEFT JOIN或LEFT OUTER JOIN:

From this link I understand that .Include(...) determines to do a LEFT JOIN or a LEFT OUTER JOIN depending on the nullability of the foreign key:

Code First根据外键的可空性推断关系的多重性.如果该属性可为空,则该关系将注册为可选.

Code First infers the multiplicity of the relationship based on the nullability of the foreign key. If the property is nullable then the relationship is registered as optional.

因为那不是发生的情况,所以缺少一些东西.

As that isn't what happens, there is something missing.

无论是否填充其位置,都需要进行哪些修改才能返回所有项目?

谢谢!

推荐答案

您可以在 Include()之后使用 DefaultIfEmpty()方法.

You can use DefaultIfEmpty() method after Include().

例如:

var projects = dbContext.Projects.Include(x => x.Location).DefaultIfEmpty()...;

这篇关于使用C#EF Core返回包含零孩子的父母.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆