gpt4 book ai didi

c# - 为什么我不能在我的 LINQ 语句中执行超过一级的包含?

转载 作者:行者123 更新时间:2023-11-30 20:55:57 26 4
gpt4 key购买 nike

我正在使用 Entity Framework 5 并且我有这些类:

public partial class Subject
{
public int SubjectId { get; set; }
public string Name { get; set; }
public virtual ICollection<Topic> Topics { get; set; }
}

public partial class Topic
{
public int TopicId { get; set; }
public string Name { get; set; }
public int SubjectId { get; set; }
public virtual Subject Subject { get; set; }
public virtual ICollection<SubTopic> SubTopics { get; set; }
}

public partial class SubTopic
{
public int SubTopicId { get; set; }
public string Name { get; set; }
public int TopicId { get; set; }
public virtual Topic Topic { get; set; }
}

现在我正在尝试编写一个 LINQ 查询来填充此类:

public class TopicSubTopicSelect
{
public int TopicId { get; set; }
public int SubTopicId { get; set; }
public string TopicName { get; set; }
public string SubTopicName { get; set; }
}

到目前为止我有这个:

        return _subjectsRepository
.GetAll()
.Where(s => s.SubjectId == subjectId)
.Include(s => s.Topics)
.Include(s => s.Topics.) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
.AsEnumerable()
.Select(item => new TopicSubTopicSelect(item.TopicId,
item.SubTopicId,
item.Topic.Name,
item.Name))
.ToList();

但是它在我放置 <<<<<

的那一行给了我一个错误

我想要的是 .Include(s => s.Topics.SubTopics)

但是智能感知并没有给我这个选项。任何想法我是什么做错了以及如何修改 LINQ 以获取数据以填充 TopicSubTopicSelect 类

最佳答案

这会给你想要的结果-

.Include(s => s.Topics.SelectMany(t => t.SubTopics))

如果 SubTopic 是一个 property,则使用 .Select,但如果是一个 list,则使用 。 SelectMany.

有关更多说明,请参阅 Select Vs SelectMany .

关于c# - 为什么我不能在我的 LINQ 语句中执行超过一级的包含?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17899919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com