如何获取连接表数据实体框架

时间:2015-07-11 12:13:41

标签: linq entity-framework ef-code-first

我有两个模型

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string ShortDescription { get; set; }
    public string PostImage { get; set; }
    public string Thumbnail { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime? PublishedDate { get; set; }
    public string  CreatedBy { get; set; }

    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

这会生成CategoryPosts表。

这是我的问题:我想从CategoryPosts表中获取数据来计算热门类别。我该如何获得这些数据?最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

如果您想要热门类别而不需要映射juction表,可以按帖子的顺序订购Categories

var query=yourContext.Categories.OrderBy(c=>c.Posts.Count);

如果您已禁用延迟加载,则应在之前调用Include方法:

var query=yourContext.Categories.Include(c=>c.Posts).OrderBy(c=>c.Posts.Count);

如下所示,生成的SQL代码使用联结表来检查每个Post的{​​{1}}的数量,并按该条件排序:

Category

当您需要添加其他列(排除要加入的表的两个键)时,通常会映射联结表。在这种情况下,您需要在juction表与SELECT [Project1].[Id] AS [Id], [Project1].[Name] AS [Name] FROM ( SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], (SELECT COUNT(1) AS [A1] FROM [dbo].[PostCategories] AS [Extent2] WHERE [Extent1].[Id] = [Extent2].[Category_Id]) AS [C1] FROM [dbo].[Categories] AS [Extent1] ) AS [Project1] ORDER BY [Project1].[C1] ASC Post之间创建两个一对多关系。

答案 1 :(得分:0)

感谢octavio,

我现在明白我的想法很容易就是这样。

   public List<Category> GetPopularCategories()
    {
     return _categoryRepository.GetAll().OrderBy(c => c.Posts.Count).ToList();
    }