I often find myself with a list of disconnected Linq2Sql objects or keys that I need to re-select from a Linq2Sql data-context to update or delete in the database. If this were SQL, I would use IN
in the SQL WHERE
clause, but I am stuck with what to do in Linq2Sql. Here is a sample of what I would like to write:
public void MarkValidated(IList<int> idsToValidate)
{
using(_Db.NewSession()) // Instatiates new DataContext
{
// ThatAreIn <- this is where I am stuck
var items = _Db.Items.ThatAreIn(idsToValidate).ToList();
foreach(var item in items)
item.Validated = DateTime.Now;
_Db.SubmitChanges();
} // Disposes of DataContext
}
Or:
public void DeleteItems(IList<int> idsToDelete)
{
using(_Db.NewSession()) // Instatiates new DataContext
{
// ThatAreIn <- this is where I am stuck
var items = _Db.Items.ThatAreIn(idsToValidate);
_Db.Items.DeleteAllOnSubmit(items);
_Db.SubmitChanges();
} // Disposes of DataContext
}
Can I get this done in one trip to the database? If so, how? Is it possible to send all those ints to the database as a list of parameters and is that more efficient开发者_如何学Python than doing a foreach over the list to select each item one at a time?
Can you do:
var items = _Db.Items.Where(i => idsToValidate.Contains(i.Key));
Will that work or am I missing something?
精彩评论