views:

345

answers:

2

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?

A: 

There are two ways, at least two I can think of:

  1. Have an entity for each object, this is nasty and it is, as usual hard to get the wiring correct.
  2. 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.

David McEwing
Thanks. That is what I did. Removed the middle class. So in the model it is a Many To Many and the CategoryProduct is gone.
Shuaib
+2  A: 

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

Alex James
Thanks Alex. But how can I endit the columns of a product?I get this error: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.The code is:public static int Update(Product c) { using (SimvideoEntities ctx = new SimvideoEntities()) { ctx.Attach(c); Common.SetModified(ctx, c); return ctx.SaveChanges(true); } }
Shuaib
Shuaib
Shuaib you should check out my blog and series of tips. In particular Tip 26 which will help you avoid unnecessary database queries.
Alex James
Thanks Alex that helped alot. Keep up the good work.
Shuaib