2011-12-30 123 views
0

我在我的仓库下面的代码:EF代码优先选择基于许多行一对多的关系

public PagedResult<Post> GetAllPublishedByTag(int tagId, int start, int max) 
{ 
    var query = Database.Set<Post>().Where(p => p.IsPublished) 
            .OrderByDescending(p => p.CreatedAt) 
            .Skip(start) 
            .Take(max); 

    int total = query.Count(); 
    var result = query.ToList(); 

    return new PagedResult<Post>(result, total); 
} 

这会给我发布的所有职位。但我想要的是为某个标签选择所有发布的帖子。我的模型的设置方式是标签与帖子之间有多对多的关系。我想稍微修改上面的代码,但是这并不工作:

public PagedResult<Post> GetAllPublishedByTag(Tag tag, int start, int max) 
{ 
    var query = Database.Set<Post>().Where(p => p.Tags.Contains(tag) && p.IsPublished) 
            .OrderByDescending(p => p.CreatedAt) 
            .Skip(start) 
            .Take(max); 

    int total = query.Count(); 
    var result = query.ToList(); 

    return new PagedResult<Post>(result, total); 
} 

我宁愿在标签识别通过(按第一个代码示例),而不是标签对象,但不知道如何正确地写LINQ声明。

回答

1
var query = Database.Set<Post>().Where(p => p.Tags.Any(t => t.Id == tagId) && p.IsPublished) 
.OrderByDescending(p => p.CreatedAt) 
.Skip(start) 
.Take(max); 

侧注:我相信你可能有你的分页问题,​​因为变量总计是在skip/take被调用后计算的。