简体   繁体   English

ASP.NET MVC3和LINQ使用映射表选择

[英]ASP.NET MVC3 & LINQ Select using mapping table

On SQL I have 3 tables: Organization(id, name) , Category(id, name) , Catalog(org_id, cat_id) - mapping table between Organizations and Categories. 在SQL上,我有3个表: Organization(id,name)Category(id,name)Catalog(org_id,cat_id)-Organizations和Categories之间的映射表。 ADO.NET DbContext Generator created for me 2 classes: ADO.NET DbContext Generator为我创建了2个类:

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; }
}

How can I select all organizations that mapped to cat_id = 1 using LINQ ? 如何选择使用LINQ映射到cat_id = 1的所有组织 Like I do it using t-sql: 就像我用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

I tried 我试过了

var model = _db.Category
            .Where(c => c.id == 1)
            .Select(c => c.Organization);

But I have troubles with type defined in view like 但是我在视图中定义的类型有麻烦

@model IEnumerable<Project1.Models.Organization>

From your code there I can only presume that you're not creating an Enumerable from the query. 从您的代码中,我只能假定您没有从查询中创建一个Enumerable。 Your code: 您的代码:

var model = _db.Category.Where(c => c.id == 1).Select(c => c.Organization);

Is not an enumerable as your model is defined. 在定义模型时不可枚举。 Try: 尝试:

var model = _db.Category.Single(c => c.id == 1).Organizations.ToList();

Which will convert the query into an enumeration of the results, which would then satisfy the requirements of your model. 它将查询转换为结果的枚举,然后将满足模型的要求。

EDIT On second looks, it appears that your model is not a 1:M relationship, which could be the issue you're having. 编辑在第二眼看来,您的模型似乎不是1:M关系,这可能是您遇到的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM