tags:

views:

76

answers:

2

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 than doing a foreach over the list to select each item one at a time?

+3  A: 

Hey,

Can you do:

var items = _Db.Items.Where(i => idsToValidate.Contains(i.Key));

Will that work or am I missing something?

Brian
<slapsForeHead>I knew that.</slapsForeHead>
flipdoubt
+1  A: 

See also http://stackoverflow.com/questions/374267/contains-workaround-using-linq-to-entities

Hightechrider
This is interesting, but it only works for Linq-to-Entities, not Linq-to-Sql.
flipdoubt
It looks like the BuildContainsExpression link that points to MSDN works on Linq2Sql too.
flipdoubt