ASP.NET MVC3 & LINQ Select using mapping table
本文关键字:Select using mapping table LINQ NET MVC3 amp ASP | 更新日期: 2023-09-27 18:35:28
在SQL上,我有3个表:Organization(id,name),Category(id,name),Catalog(org_id,cat_id) - 组织和类别之间的映射表。ADO.NET 为我创建了 2 个类的 DbContext 生成器:
public partial class Organization
{
public Organization()
{
this.Category = new HashSet<Category>();
}
public int id { get; set; }
public string name { get; set; }
public virtual ICollection<Category> Category { get; set; }
}
public partial class Category
{
public Category()
{
this.Organization = new HashSet<Organization>();
}
public int id { get; set; }
public string name { get; set; }
public virtual ICollection<Organization> Organization { get; set; }
}
如何使用 LINQ 选择映射到 cat_id = 1 的所有组织?就像我使用 t-sql 一样:
SELECT *
FROM Organization o
INNER JOIN Catalog ct ON o.id = ct.org_id
INNER JOIN Category cg ON ct.cat_id = cg.id
WHERE cg.id = 1
我试过了
var model = _db.Category
.Where(c => c.id == 1)
.Select(c => c.Organization);
但是我对视图中定义的类型有麻烦,例如
@model IEnumerable<Project1.Models.Organization>
从您的代码中,我只能假设您没有从查询创建枚举。您的代码:
var model = _db.Category.Where(c => c.id == 1).Select(c => c.Organization);
不是模型定义的可枚举对象。尝试:
var model = _db.Category.Single(c => c.id == 1).Organizations.ToList();
这会将查询转换为结果的枚举,然后满足模型的要求。
编辑再看一眼,您的模型似乎不是 1:M 关系,这可能是您遇到的问题。