Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Many To Many CRUD

I am playing around with Entity Framework for a POC project. In my database I have

Category<-------CategoryProduct ------->Product

(Where the join table is an entity in the model.)

How can I do select / insert / update or delete on this?

like image 729
Shuaib Avatar asked Jul 24 '09 00:07

Shuaib


1 Answers

Assuming the CategoryProduct table is simply made up of two FKs one to Product and one to Category... the EF will by default not produce a CategoryProduct entity, instead to manipulate that table you will need to create / delete relationships using Product.Categories or Category.Products collections.

I.e. to add a row:

product.Categories.Add(category); // or category.Products.Add(product);

To remove a row:

product.Categories.Remove(category); // or visa versa

To query the table i.e. to get the rows in that table:

var pc = from c in ctx.Categories
         from p in c.Products
         select new {CategoryID = c.ID, ProductID = p.ID};

And update doesn't make sense, because the PK (which can't change) is all the columns, i.e. none of the row's columns can be update, so the row itself can't be updated (excluding deletes of course).

Hope this helps

Alex James

like image 71
Alex James Avatar answered Sep 30 '22 20:09

Alex James