【问题标题】:Include when don't know exact type [duplicate]包括不知道确切类型时[重复]
【发布时间】:2020-05-21 12:25:56
【问题描述】:

我有 3 种类型的帖子:PostAPostBPostC,它们都继承自 Post。我在 Context.cs 中为所有这些定义了一个表,如下所示: public DbSet<Post> Posts { get; set; }

现在我需要根据 Id 检索信息,但不知道如何使用 Includes 查询。

Post post = _context.Posts
    .Include(p => p.AddedBy)
    .Include(p => p.Responses)
        .ThenInclude(res => res.User)
    .Include(p => p.Responses)
        .ThenInclude(res => res.Comments)

    //.OfType<PostA>()
    //    .Include(a => a.PostATags)
    //        .ThenInclude(r => r.Tag)
    //.OfType<PostB>()
    //    .Include(b => b.Article)

    .FirstOrDefault(p => p.Id == id);

我不知道查询时的类型,所以我不能在这里申请OfType&lt;&gt;()。上面的查询有效,但不包括我需要的所有数据。

【问题讨论】:

  • 接受的答案打了 2 个电话,但第二个答案很有帮助。我将在下面粘贴解决方案

标签: c# entity-framework entity-framework-core


【解决方案1】:

我是这样实现的:

Post post = _context.Posts
    .Include(p => p.AddedBy)
    .Include(p=> p.Responses)
        .ThenInclude(res => res.User)
    .Include(p => p.Responses)
        .ThenInclude(res => res.Comments)

    .Include(p => (p as PostA).PostATags)
        .ThenInclude(r => r.Tag)
    .Include(p => (p as PostB).Article)

    .FirstOrDefault(p => p.Id == id);

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多