entity framework - EF 6 - many-to-many - Join table without duplicates -
i'm using ef6 have confusion on seeding many many relationship.
i have following:
a user
has many saved chartqueries
(that can execute chart). chartquery
typically belongs 1 user, there several "shared" chartquery
s every user
can execute. result set many many relationship using join table userchartquery
. tables in database fine @ 1-to-many on each side of join table.
however, i'm not quite understanding how seed or use relationship. don't want end several duplicates of "shared" chartquery
s (a duplicate each user
). instead, there should single row each "shared" chartquery
part of each user
's savedchartqueries
collection (along other, non-shared chartquery
s belong user
only).
it seems i'm forced duplicate each user:
var sharedchartquery = new chartquery { ... }; var nonsharedchartquery = new chartquery { ... }; var useronechartqueryone = new userchartquery { user = userone, chartquery = sharedchartquery }; var usertwochartqueryone = new userchartquery { user = usertwo, chartquery = sharedchartquery }; var usertwochartquerytwo = new userchartquery { user = usertwo, chartquery = nonsharedchartquery }; context.userchartqueries.add(useronechartqueryone); context.userchartqueries.add(useronechartquerytwo); context.userchartqueries.add(usertwochartquerytwo);
so first of right way seed (through userchartqueries table directly) or should seed each user
's savedchartqueries navigation property?
and result in duplicate sharedchartquery
in join table each user
? if there way avoid this?
ok understand how works now. following works expected:
var userone = new user {}; var usertwo = new user {}; var chartquery = new chartquery { }; context.users.add(userone); context.users.add(usertwo); context.userchartqueries.add(new userchartquery { user = userone, chartquery = chartquery }); context.userchartqueries.add(new userchartquery { user = usertwo, chartquery = chartquery }); context.chartqueries.add(chartquery);
the last line adds table record resides. checking join table in ssms shows holds foreign keys , nothing else. there no duplicates.
Comments
Post a Comment