I have two SQL tables in my database. Here they are represented as C# classes:
public class Topic
{
public Topic()
{
this.SubTopics = new HashSet<SubTopic>();
}
public int TopicId { get; set; }
public string Name { get; set; }
public int Number { get; set; }
public virtual ICollection<SubTopic> SubTopics { get; set; }
}
public class SubTopic
{
public int SubTopicId { get; set; }
public int TopicId { get; set; }
public string Name { get; set; }
public virtual Topic Topic { get; set; }
}
I created this code to get a simple list:
var result = db.SubTopics
.Select(s => new
{
TopicId = s.TopicId,
SubTopicId = s.SubTopicId,
TopicName = s.Topic.Name,
SubTopicName = s.Name
})
.ToListAsync();
Result here but it only works if I have a SubTopic for every Topic:
Topic1 SubTopic1 abc def
Topic1 SubTopic2 ghi jkl
Topic2 SubTopic3 mno pqr
Topic3 SubTopic4 stu vwx
Topic3 SubTopic5 xxx yyy
I would like to get a result looking like this for the cases where I don't have a Subtopic for every Topic:
Topic1 SubTopic1 abc def
Topic1 SubTopic2 ghi jkl
Topic2 null mno null
Topic3 SubTopic4 stu vwx
Topic3 SubTopic5 xxx yyy
or a result like this if there were no SubTopics at all:
Topic1 null abc null
Topic2 null mno null
Topic3 null stu null
Can someone give me some advice how I could get this using LINQ. I assume I would need to first target like this:
var result = db.Topics
But I am not sure how I can add in the SubTopics and have it work for the case where there are sometimes no matching SubTopics.