查询不返回子集合 [英] Query does not return child collections

查看:81
本文介绍了查询不返回子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然对此感到困惑,为什么每个类别"项都返回空的任务"集合.我的数据库中确实有数据,我缺少什么?

I still struggle with this, why each of 'Category' items returns null 'Task' collections. I do have data in the database, what am I missing?

public class ApplicationUser : IdentityUser
{
    public ICollection<Category> Categories { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public DateTime Timestamp { get; set; }

    public ICollection<Task> Tasks { get; set; }
}

public class Task
{
    public int TaskId { get; set; }
    public string Name { get; set; }
    public DateTime Timestamp { get; set; }
}

这是查询:

public IEnumerable<Category> GetAllForUser(string name)
{
    return _ctx.Users.Where(x => x.UserName == name)
                     .SelectMany(x => x.Categories)
                     .Include(x => x.Tasks).ToList();    
}

推荐答案

您的查询属于

如果更改查询以使其不再返回查询开始的实体类型的实例,则将忽略include运算符.

If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored.

如链接中所述,如果将以下内容添加到DbContext OnConfiguring:

As explained in the link, if you add the following to your DbContext OnConfiguring:

optionsBuilder.ConfigureWarnings(warnings => warnings.Throw(CoreEventId.IncludeIgnoredWarning));

然后改为null集合,您将得到InvalidOperationException,其中包含类似以下内容的错误消息:

then instead null collection you'll get InvalidOperationException containing something like this inside the error message:

导航的"include"操作:"x.Tasks"被忽略了,因为在最终查询结果中无法达到目标导航.

The Include operation for navigation: 'x.Tasks' was ignored because the target navigation is not reachable in the final query results.

那该如何解决呢?显然,要求是从要为其添加包含的实体开始查询.对于您的情况,您应该从_ctx.Categories开始.但是,为了应用相同的过滤器,您需要将Application.Users的反向导航属性添加到Category类:

So how to fix that? Apparently the requirement is to start the query from the entity for which you want to add includes. In your case, you should start from _ctx.Categories. But in order to apply the same filter, you need to add the reverse navigation property of the Application.Users to the Category class:

public class Category
{
    // ...
    public ApplicationUser ApplicationUser { get; set; }
}

现在,以下内容将起作用:

Now the following will work:

public IEnumerable<Category> GetAllForUser(string name)
{
    return _ctx.Categories
        .Where(c => c.ApplicationUser.UserName == name)
        .Include(c => c.Tasks)
        .ToList();    
}

这篇关于查询不返回子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆