I’m working with a DataContext object and Linq to SQL in c#. I’m attempting to transfer the votes for a wish on a wishlist to a question that the administrator has determined that the first question is a duplicate of. However, since the vote table has the WishId and UserId as primary keys, if the user has already voted on the destination wish, then the insert will fail. What I would like to do is ignore these cases (without querying the vote table before inserting) and insert all the valid votes. This is what I would like to do.
using (linqWishesDataContext dataContext = new linqWishesDataContext())
{
try
{
dataContext.WishlistUpvotes.InsertAllOnSubmit(destinationVotes);
dataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch{}
}
One solution I have right now is to do this:
foreach (WishlistUpvote vote in destinationVotes)
{
using (linqWishesDataContext dataContext = new linqWishesDataContext())
{
try
{
dataContext.WishlistUpvotes.InsertOnSubmit(vote);
dataContext.SubmitChanges();
}
catch { }
}
}
But if there are a couple hundred or a couple thousand votes that need moved then it seems like a bad idea to create a new DataContext for each vote. Any suggestions?
There’s no need to create a new
DataContexteach time; you can reuse the same one, and simply loop your calls as you are now, otherwise.Of course, this will issue individual commands for each update. (though ADO.NET connection pooling will still be working behind the scenes, so it’s not that horrible) Without manually building the SQL for inserts, I don’t know what else you could do. The data context will do all changes for one call to
SubmitChanges()in a transaction, which is why you get the ‘all or nothing’ behavior.