【问题标题】:Entity Framework Select with many tables One-to-Many实体框架选择多表一对多
【发布时间】:2021-05-25 09:17:20
【问题描述】:

下面三个表格:

关系:

  1. 作者与 AuthorBiography 是一对一的
  2. 作者与 AuthorPrix 是一对多的

我会在 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

我可以这样做:

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

但我无法将字段 [Prix Name] 添加到选择中。 仍然可以使用简单的 Select 还是我应该使用 Join?

提前感谢您的帮助。

【问题讨论】:

    标签: c# sql-server entity-framework select entity-framework-core


    【解决方案1】:

    您可以像这样将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();
    

    【讨论】:

    • 伙计们,为什么要添加Include 进行自定义投影?
    • 感谢您的帮助,我忘记回复您并检查已接受的答案标志。
    猜你喜欢
    • 2012-05-28
    • 2010-10-29
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    相关资源
    最近更新 更多