1

我想从 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; }
    }

谢谢

4

2 回答 2

3

尝试这个

 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();
于 2021-07-22T00:34:14.340 回答
1

从表标签开始使用它的替代方法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 中,可以在没有连接表的实体类的情况下创建多对多关系。

于 2021-07-22T01:45:50.703 回答