I'm using entity framework database first.

For one to many relation, in sql server, I use the following sql query(Status_ID is foreign key):

SELECT Products.*, Status.Title as Pstatus
FROM Products, Status 
WHERE Products.Status_ID = Status.ID

In MVC I use the following code to retrieve the same data as above sql query and pass the list to the View:

Controller:

var products = oDB.Products.Include(m => m.Status)
                       .ToList();
// string test = products[0].Status.Title;
return View(products);

In the view I can access the desired data by the following code:

View:

@model List<myDB.Product>
...
@item.Status.Title // This works well for each item in the list

For MANY TO MANY RELATIONS WITH JUNCTION TABLE, this is my .edmx:

enter image description here

Now How could I retrieve list of products including related categories? I need the list of products and pas it to the view as a list, and access each product's categories in the view.

My Classes (These classes are generated automatically):

public partial class Category
{
    public int ID { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Products_Categories> Products_Categories { get; set; }
}

public partial class Products_Categories
{
    public int ID { get; set; }
    public Nullable<int> Product_ID { get; set; }
    public Nullable<int> Category_ID { get; set; }
    public virtual Category Category { get; set; }
    public virtual Product Product { get; set; }
}

public partial class Product
{
    public int ID { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Products_Categories> Products_Categories { get; set; }
}

Related posts

Recent Viewed