0

我有一个关系,项目类别。这种关系是多对多的,所以我有三个表: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);
}

但这给出了错误:

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

我究竟做错了什么?

4

3 回答 3

1

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

var id = int.Parse(catID);
Adapter.ProjectRepository.Get().Where(x => x.Categories.Any(y => y.CategoryID == id))
于 2013-08-26T13:40:04.767 回答
1

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

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

用于Any检查是否存在Categoryid 等于您的值的对象:

  var projects = Adapter.ProjectRepository.Get()
                        .Where(x => x.Categories.Any(c => c.CategoryID == catID))
于 2013-08-26T13:33:48.003 回答
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();

从另一个方向查询它

于 2013-08-26T13:35:02.607 回答