【问题标题】:problem with inner join in many-to-many relationships with entity framework core 5与实体框架核心5的多对多关系中的内部连接问题
【发布时间】:2021-10-14 23:02:15
【问题描述】:

我想跨两个多对多相关的表发起查询,并且在实体框架核心 5 中,没有必要创建中间表的 c# 类。因此,使用 include 时,我使用正确的左连接启动查询,但我需要启动内连接,但我不能,因为我没有中间表的 c# 类。不用创建中间表的c#类怎么可能做到这一点?

非常感谢

【问题讨论】:

  • 您必须在每个单侧实体中使用虚拟集合

标签: c# entity-framework-core entity-framework-5 .net-5


【解决方案1】:

您不需要中间实体即可在 LINQ to Entities 查询中实现内部联接。你只需要SelectMany 没有DefaultIfEmpty()

例如,使用文档Many-to-many 部分中的示例模型:

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public ICollection<Post> Posts { get; set; }
}

以下将生成内部连接:

var query = from post in db.Posts
            from tag in post.Tags
            select new { post, tag };

或使用方法语法

var query = db.Posts
    .SelectMany(post => post.Tags, (post, tag) => new { post, tag });

【讨论】:

  • 非常感谢,实际上是这样跨表的:from post in db.Posts from tag in post.Tags 我已经强制启动了我真正需要的内连接,我没想过像这样进行交叉这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
相关资源
最近更新 更多