Lets say I have a simple table that only contains two columns:
MailingListUser
- PK ID (int)
- FK UserID (int)
I have a method called UpdateMailList(IEnumerable
. <int
> userIDs)
How do I, in LINQ, make inserts for the userIDs that are present in the passed in parameter but don't exist in the db, delete the ones that are in the db but no longer in UserIDs, and leave the ones that are already in both the db and userIDs alone?
A user is presented with a checkbox list, and when it first loads it has the existing members selected for the maillist checked.
The user can then check and uncheck various users and hit "save". Once this happens, I need to update the state of the database with the state of the checklist.
Here is what I'm doing now:
public void UpdateMailList(IEnumerable<int> userIDs)
{
using (MainDataContext db = new MainDataContext())
{
var existingUsers = (from a in db.MailListUsers
select a);
db.MailListUsers.DeleteAllOnSubmit(existingUsers);
db.SubmitChanges();
var newUsers = (from n in userIDs
select new MailListUser
{
UserID = n
});
db.MailListUsers.InsertAllOnSubmit(newUsers);
db.SubmitChanges();
}
}
}
}
Is there a better way than simply deleting all entries in the MailingListUser table, and re-inserting all the userIDs values?