asp.net mvc - Entity Framework query not generated -
i have following object model:
[table("apa_questionproduct")] public class questionproduct { [key, foreignkey("question"), column(order=0)] public int questionid { get; set; } [foreignkey("questionid")] public question question { get; set; } [key, foreignkey("product"), column(order=1)] public int productid { get; set; } [foreignkey("productid")] public product product { get; set; } }
table:
use [qbm] go /****** object: table [dbo].[apa_questionproduct] script date: 5/21/2013 6:52:46 pm ******/ set ansi_nulls on go set quoted_identifier on go create table [dbo].[apa_questionproduct]( [questionid] [int] not null, [productid] [int] not null, constraint [pk_apa_questionproduct] primary key clustered ( [questionid] asc, [productid] asc )with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary] ) on [primary] go alter table [dbo].[apa_questionproduct] check add constraint [fk_apa_questionproduct_apa_product] foreign key([productid]) references [dbo].[apa_product] ([productid]) go alter table [dbo].[apa_questionproduct] check constraint [fk_apa_questionproduct_apa_product] go alter table [dbo].[apa_questionproduct] check add constraint [fk_apa_questionproduct_apa_question] foreign key([questionid]) references [dbo].[apa_question] ([questionid]) go alter table [dbo].[apa_questionproduct] check constraint [fk_apa_questionproduct_apa_question] go
so table behind has 2 foreign keys (that primary keys). question object has list of products. when update productid foreign key , call 'savechanges' on context no query/update generated in db:
question.products[1].productid = 4; db.entry(question.products[1]).state = entitystate.modified; db.savechanges();
i looked in intelitrace check query no query called on questionproduct table if questionproduct object changed. why table not updated? no error thrown.
your entity questionproduct
contains key properties, no other scalar properties. entity framework not allow change (primary) key properties.
you must delete old link record , create new 1 establish new relationship, example so:
questionproduct oldproduct = question.products[1]; questionproduct newproduct = new questionproduct { questionid = question.questionid, productid = 4 }; db.questionproducts.attach(oldproduct); db.questionproducts.remove(oldproduct); db.questionproducts.add(newproduct); db.savechanges();
but should model many-to-many relationship. don't need questionproduct
entity , have collections directly refering question
product
, vice versa without having navigate through intermediate entity.
it shown here example how works.
Comments
Post a Comment