Eladian
Eladian

Reputation: 958

Asp.net MVC Entity Framework best way to retrieve data in many to many relationships

I have a question about the best way to retrieve data from many to many relationships that have been set up via entity framework.

As a simple example, let's say I have two models:

  1. Items
  2. Categories

Let's say that this is a many-to-many relationship in which an item can have many categories and a category can belong to many items.

As far as I understand, I do not need to create a third model for the Item-Category relationship as this is handled by the entity framework itself.

Thus, once everything is set up and I have used scaffolding on both of the models I end up with code similar to this:

  public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public System.Data.Entity.DbSet<TShirtWSMVC.Models.Item> Items { get; set; }

    public System.Data.Entity.DbSet<TShirtWSMVC.Models.Category> Categories { get; set; }

Now, I want to display to my view each item and its associated categories. I am aware that I can code similar to:

dbContext.Database.SqlQuery(//Query the conjunction table here)

I could also make a method named AllCategoriesForItem(int itemID) inside the database context class.

I was wondering if there are better options? Such as when using dbContext.Items.ToList() it automatically retrieving the categories for each item so the Categories list for each item isn't null.

Alternatively, is there a way to have the ItemCategory table represented in the application db context?

Thanks.

Upvotes: 1

Views: 543

Answers (1)

Denis V
Denis V

Reputation: 421

namespace YourApp.Controllers
{
    public class YourController: Controller
    {
        //your db context
        private ApplicationDbContext db = new ApplicationDbContext();

        public ActionResult Index()
        {
            var list = db.Items.Include(c => c.Categories);
            return View(list.toList());
        }
     }
}

That's your controller, now you have to use it on your view.

Upvotes: 1

Related Questions