c# - Inserting a list of complex objects to the database -
in application i'm going have list of complex object i'm going insert database.
list attached user, thought adding column list of ids users
table, , have app convert list complex objects using list of ids.
for example; user have 3 subjects
ids: "2,3,23"
.
each subject
has name, grade, etc...
on runtime, app go through each id , properties database , add complete subject list.
the problem sounds quite inefficient honest.
, therefore, question is; is there way more efficiently?
the normal way have separate table subjects , table has userid foreign key owning user record.
then don't have mess editing comma-separated string. allows define foreign-key constraint (as long db can it) stop inserting subjects record userid doesn't exist in user table.
to load subjects user, retrieve records subjects table id of user.
if many-to-many relationship more appropriate, user can linked many subjects , subject can linked may users, use join table, usersubjectjoin contains each userid , subjectid pairing. again, can have constraints ensure ids must exist in users , subjects tables.
in scenario, need join usersubjectjoin table subjects table retrieve subjects records userid specify.
to answer question fully, more efficient because don't have maintain column of strings in users table add/delete rows subjects table , associations automatically updated.
and if have many-to-many relationship, under initial design need have column of userids on subjects table doubles maintenance, , risk of getting wrong.
Comments
Post a Comment