1

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; }
}
Muhamad Jafarnejad
  • 2,521
  • 4
  • 21
  • 34
  • See this question: http://stackoverflow.com/questions/10822656/entity-framework-include-multiple-levels-of-properties and MSDN: https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx – Peter B Dec 13 '16 at 09:23
  • Can you show us the sets that are currently available in your oDB? As @PeterB pointed out, the key is to include the sets that you need. – Razvan Dumitru Dec 13 '16 at 09:23

2 Answers2

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

and in a view you could use it like this

@foreach(var item in model){ 
   <h3>string.join(", ", item.Product_Categories.Select(pc=>pc.Category.Title))</h3> 
}
Alexander Taran
  • 6,655
  • 2
  • 39
  • 60
1

You need to use something like this:

var products = oDB.Products.Include("Status")
                   .ToList();
// string test = products[0].Status.Title;
return View(products);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128