简体   繁体   English

实体框架 Select 与许多表一对多

[英]Entity Framework Select with many tables One-to-Many

With the three tables below:与下面的三个表:

在此处输入图像描述

Relationship:关系:

  1. Author is one-to-one with AuthorBiography作者与 AuthorBiography 是一对一的
  2. Author is one-to-many with AuthorPrix作者与 AuthorPrix 是一对多的

and I would perform a query using method syntax in EF Core and Select to limit the fields to return.我将使用 EF Core 和 Select 中的方法语法执行查询,以限制要返回的字段。

SELECT a.FirstName, a.LastName, ab.Biography, ap.PrixName
FROM dbo.Author AS a
LEFT JOIN dbo.AuthorBiography AS ab ON a.AuthorId = ab.AuthorRef
LEFT JOIN dbo.AuthorPrix AS ap ON a.AuthorId = ap.AuthorRef

I can do like that:我可以这样做:

var a = dbCtx.Author
                .Include(b => b.AuthorBiography)
                .Include(c => c.AuthorPrixes)
                .Select(a => new { a.FirstName, a.LastName, a.AuthorBiography.Biography })
                .ToList();

But I cannot add the field [Prix Name] to the select.但我无法将字段 [Prix Name] 添加到 select。 Is still possible using a simple Select or I should use a Join?仍然可以使用简单的 Select 还是我应该使用加入?

Thanks in advance for your help.在此先感谢您的帮助。

You can add SelectMany to your linq query like this:您可以像这样将SelectMany添加到 linq 查询中:

var a = dbCtx.Author
        .Include(b => b.AuthorBiography)
        .Include(c => c.AuthorPrixes)
        .SelectMany(a => a.AuthorPrixes)
        .Select(a => new { a.PrixName, a.Author.FirstName, a.Author.LastName, a.Author.AuthorBiography.Biography })
                .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM