【问题标题】:Linq method - Return rows only found in another tableLinq 方法 - 返回仅在另一个表中找到的行
【发布时间】:2021-09-29 07:39:12
【问题描述】:

我想从 Tag 表中返回仅在 TagRecipe 表中找到的标签。我该怎么做?

            var dataTags = await _context.Tags
                .Include(tc => tc.TagCategory)
                .ToListAsync();
    public class Tag
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public ICollection<TagRecipe> TagRecipes { get; set; }

        public int TagCategoryID { get; set; }
        public TagCategory TagCategory { get; set; }
    }
    public class TagRecipe
    {
        public int TagId { get; set; }
        public int RecipeId { get; set; }
        public Tag Tag { get; set; }
        public Recipe Recipe { get; set; }
    }

谢谢

【问题讨论】:

  • 能否请您同时发布表格模型的标签和标签食谱?
  • 没问题,完成。

标签: c# asp.net-core .net-core entity-framework-core linq-method-syntax


【解决方案1】:

试试这个

 var dataTags = await _context.TagRecipe
                .Include(tc => tc.Tag.TagCategory)
                .Select(i=> i.Tag)
                .ToListAsync();

或者如果你更喜欢这个语法,你可以使用它

var dataTags = await _context.TagRecipe
                .Include(t => t.Tag)
                .ThenInclude(tc => tc.TagCategory)
                .Select(i=> i.Tag)
                .ToListAsync();

【讨论】:

  • Serge:我相信你错过了.Distinct。想象一下连接表 TagRecipe 包含 5 条 TagId = 1 的记录的情况。
【解决方案2】:

从表 Tags 开始使用Join 的替代方法将返回没有重复的结果。

var dataTags = db.Tags
    .Join(db.TagRecipes, tag => tag.Id, tagRecipe => tagRecipe.TagId, (tag, tagRecipe) => tag)
    .Include(tag => tag.TagCategory)
    .ToLookup(tag => tag.Id) // client-side from here
    .Select(grouping => grouping.First()) // to make distinct
    .ToList();

将生成一个直截了当的 SQL

SELECT "t"."Id", "t"."Name", "t"."TagCategoryId", "t1"."Id", "t1"."Name"
FROM "Tags" AS "t"
INNER JOIN "TagRecipes" AS "t0" ON "t"."Id" = "t0"."TagId"
INNER JOIN "TagCategories" AS "t1" ON "t"."TagCategoryId" = "t1"."Id"

可以在上面的表达式中使用.Distinct 来删除重复项而不是使用分组,但这会创建更复杂的 SQL。

TagRecipes 似乎是表 Tags 和表 Recipes 之间的多对多连接表。后者未包含在问题中,但我在测试期间添加了它。

请注意,在 EF Core 5 中,多对多关系可能会在没有连接表的实体类的情况下创建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    相关资源
    最近更新 更多