I have a join table of Person's Sports with the following schema:
PersonId
SportID
How do I effectively set Person's sports in one transaction i.e.
void SetPersonsSports(List<PersonsSportsL> sports);
My way of doing it was deleteing all person's sports with x.PersonId = PersonId first and then adding all sports back in but I know that delete operation is expensive and wanted to see what other people are doing when faced with a similar task.
Thank you.
UPDATE:
Here's what I was thinking....
void SetPersonsSports(List<PersonsSports> PersonSports)
{
using (DataContext dc = conn.GetContext())
{
if (PersonSports.Select(x=>x.PersonID).Distinct().Count()>1)
throw new Exception("This method can only be used with a set of sports for the same person ID at a time");
var sportIDs = PersonSports.Select(x=>x.SportID);
bool submitFlag = false;
var toRemove = dc.PersonSports.Where(x=>!sportIDs.Contains(x.SportID));
if (toRemove.Count()>0)
{
dc.PersonSports.DeleteAllOnSubmit(toRemove);
submitFlag = true;
}
var toAdd = dc.PersonSports.Where(x=>!sportIDs.Contains(x.SportID));
if (toAdd.Count()>0)
{
dc.PersonSports.InsertAllOnSubmit(toAdd);
submitFlag = true;
}
if (submitFlag)
dc.SubmitChanges();
}
}