Let's say I have a simple table containing only two columns:
MailingListUser
- PK ID (int)
- FK UserID (int)
I have a method called .UpdateMailList(IEnumerable<int > userIDs)
How do I insert in LINQ inserts for user IDs that are present in the pass parameter but do not exist in db, delete those that are in db but no longer enter user IDs, and leave them that are already in db and in userIDs?
The user is provided with a list of checkboxes, and when he first loads, he has existing items selected for the maillist being checked.
Then the user can check and uncheck different users and click "save." As soon as this happens, I need to update the state of the database with the state of the checklist.
Here is what I am 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 just deleting all the entries in the MailingListUser table and reinserting all the user ID values?
source
share