LINQ select语句有多对多

时间:2013-08-26 13:29:57

标签: c# linq

我有一个关系,项目类别。这个关系很多,所以我有三个表:Project / project_has_category / categories。

我需要选择与某个类别(通过其ID)

有关系的所有项目

项目类

public class Project
{
    public int ProjectID { get; set; }

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

类别类

public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }

    public virtual ICollection<Project> Projects { get; set; }
}

我尝试了以下内容:

[HttpPost]
public ActionResult Projects(string catID, string strSearch)
{
    var cats = Adapter.CategoryRepository.Get();
    var projects = Adapter.ProjectRepository.Get().Where(x => x.Categories.Contains(catID));
    /*also*/
    var projects = Adapter.ProjectRepository.Get().Where(x => cats.Contains(catID));
    return View(projects);
}

但这会产生错误:

  

最佳重载方法匹配   &#39; System.Collections.Generic.ICollection.Contains(LibModels.Category)&#39;   有一些无效的   参数C:\ Users \ thomas \ Desktop \ Freelauncher1005 \ Freelauncher \ Controllers \ ProjectController.cs

我做错了什么?

3 个答案:

答案 0 :(得分:1)

类别是Category个对象的列表,您不能使用Contains方法搜索整数ID(检查此方法的签名 - 它需要Category个对象来搜索):

  var projects = Adapter.ProjectRepository.Get()
                        .Where(x => x.Categories.Contains(catID)) // error

使用Any检查ID为Category的对象是否等于您的值:

  var projects = Adapter.ProjectRepository.Get()
                        .Where(x => x.Categories.Any(c => c.CategoryID == catID))

答案 1 :(得分:1)

您需要先将ID转换为int,然后使用Any

var id = int.Parse(catID);
Adapter.ProjectRepository.Get().Where(x => x.Categories.Any(y => y.CategoryID == id))

答案 2 :(得分:0)

var projects = Adapter.ProjectRepository
                      .Get()
                      .Where(p => p.Categories
                                   .Any(c => c.CategoryID == catID));

或可能

var projects = Adapter.CategoryRepository
                      .Get()
                      .Where(c => c.CategoryID == catID)
                      .Select(c => c.Projects)
                      .Distinct();

从另一个方向查询