c# - EF 4.1 Code First: Many to Many -
i have 2 entities, let's , b. relation between them many-to-many have entity, let's c.
columns table a:
-id (pk) -> type int generated database
-propertya1
-propertya2
-propertya3
columns table b:
-id (pk) -> type int generated database
-description
columns table c (for table not sure if better add column id generated database previous tables):
-ida (pk , foreign key entity a)
-idb (pk , foreign key entity b)
table b has fixed values inserted on seed method (overrided). entries below:
id description
1 "some description 1"
2 "some description 2"
3 "some description 3"
from form, user introduces information related table (propertya1,...,propeprtya3) , click on button save data database.
once user clicks on button's form save data database, first following:
a = new a(){ propertya1=something_1, propertya2=something_2, propertya3=something_3 }; context.a.add(a); context.savechanges();
then after saving changes database have id generated database (i have not id before saving database), is, a.id, can proceed add entry table c doing:
b b = this.obtainappropriateb(); c c = new c(){ ida = a.id, idb = b.id }; context.c.add(c); context.savechanges();
my problem is:
1) cannot know a.id previous context.savechanges after context.a.add(a) because generated database.
2) if context.savechanges fails after context.c.add(c), how can rollback previous work done?:
context.a.add(a);
context.savechanges();
i cannot following because have not a.id previous savechanges:
a = new a(){ propertya1=something_1, propertya2=something_2, propertya3=something_3 }; context.a.add(a); b b = this.obtainappropriateb(); c c = new c(){ ida = a.id, idb = b.id }; context.c.add(c); context.savechanges(); <--- call once persist changes database
how solve this?
this not way work many-to-many relationship entity framework.
first, should not have c
entity in model instead collection properties on entity a
, b
:
public class { public int aid { get; set; } public int propertya1 { get; set; } public string propertya2 { get; set; } public datetime propertya3 { get; set; } public icollection<b> bs { get; set; } } public class b { public int bid { get; set; } // ... public icollection<a> { get; set; } }
from collections ef able figure out relationship many-to-many , link table (c
) needed. can define mapping details fluent api.
second, once have navigation collections don't need care ids. build object graph necessary relationships , save database:
a = new a() { propertya1 = something_1, propertya2 = something_2, propertya3 = something_3 }; a.bs = new list<b>(); b b = this.obtainappropriateb(); // must use same context instance a.bs.add(b); context.a.add(a); context.savechanges();
it create new a
, insert relationship row between a
, b
link table.
Comments
Post a Comment