On SQL I have 3 tables: Organization(id, name), Category(id, name), Catalog(org_id, cat_id) – mapping table between Organizations and Categories.
ADO.NET DbContext Generator created for me 2 classes:
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?
Like I do it using 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. Your code:
Is not an enumerable as your model is defined. Try:
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.