I understand that EF 2.0 does not yet support many to many joins, so I have followed the helpful details in Fluent API, many-to-many in Entity Framework Core 2.0 to query my database.
I have a table of Insights, and Topics, and the relevant join tables. An insight can have multiple topics and a topic can have multiple insights:
public class Insight
{
public int InsightId { get; set; }
[Required]
public string Heading { get; set; }
public virtual ICollection<InsightTopicJoin> InsightTopicJoins {get; set;}
}
public class InsightTopicJoin
{
public int InsightId { get; set; }
public Insight Insight {get; set;}
public int InsightTopicId { get; set; }
public InsightTopic InsightTopic {get; set;}
}
public class InsightTopic
{
public int InsightTopicId { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<InsightTopicJoin> InsightTopicJoins {get; set;}
}
My question is, how do I map the topic name as a subproperty to a DTO when querying for insights?
Currently when querying for insights by topic I use the following:
// InsightList is a DTO which I use to hide other properties (not shown here) when querying for data
public class InsightList
{
public string Heading { get; set; }
}
// This is my repository code which maps an Insight to an Insight DTO
if (TopicId == 0)
{
return await _context.Insights
.Select(p => new InsightList
{
Heading = p.Heading,
})
.ToListAsync();
}
else
{
return await _context.InsightTopics
.Where(p => p.InsightTopicId == TopicId)
.SelectMany(p=>p.InsightTopicJoins)
.Select(pc => pc.Insight)
.Select(p => new InsightList
{
Heading = p.Heading,
})
.ToListAsync();
}
I'd like to add the following property to InsightList:
public List<string> Topics { get; set;}
How do I change my query to get this data?
Update:
To be clear, currently my json result from my repository code looks like this:
{
"heading": "Test Heading",
},
I would like it to look like this:
{
"heading": "Test Heading",
"topics": [
"Topic 1",
"Topic 2"
]
},