Entity Framework Core 2.0中有许多人加入

时间:2018-01-06 22:45:47

标签: c# entity-framework

据我所知,EF 2.0尚不支持多对多联接,因此我已按照Fluent API, many-to-many in Entity Framework Core 2.0中的有用详细信息查询我的数据库。

我有一个Insights和Topics的表格以及相关的连接表。洞察可以有多个主题,主题可以有多个见解:

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;}

}

我的问题是,在查询见解时,如何将主题名称作为子属性映射到DTO?

目前,在按主题查询洞察时,我使用以下内容:

// 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();
 }

我想将以下属性添加到InsightList:

public List<string> Topics { get; set;}

如何更改查询以获取此数据?

更新

要清楚,目前我的存储库代码的json结果如下所示:

{
    "heading": "Test Heading",
},

我希望它看起来像这样:

{
    "heading": "Test Heading",
    "topics": [
        "Topic 1",
        "Topic 2"
    ]
},

1 个答案:

答案 0 :(得分:1)

你可以这样做:

.Select(p => new InsightList
{
    Heading = p.Heading,
    Topics = p.InsightTopicsJoins.Select(itj => itj.InsightTopic.Name).ToList()
}

几点建议

InsightTopic现在读起来就像一个连接表(桥表等),因为它在名称中同时包含InsightTopic这两个词。我会将它们命名如下:

Insight
Topic
InsightTopic // Or InsightToTopic (no need to mention Join in the name)

我还要将类InsightList重命名为InsightCollection,因为.NET框架遵循此约定。如果名称中包含List,则会泄漏类的内部实现;另一方面,Collection可以是任何实现,例如数组,列表,哈希集等。