Hi 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?
There are two ways, at least two I can think of:
- Have an entity for each object, this is nasty and it is, as usual hard to get the wiring correct.
- Edit the model so that it models the many-to-many relationship as a many-to-many it will then do everything for you.
Option 2 is the better way but currently has the limitation that if you have other data associated with the CategoryProduct it doesn't work.
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