How do I simulate "Is In" using Linq2Sql

Posted by flipdoubt on Stack Overflow See other posts from Stack Overflow or by flipdoubt
Published on 2010-04-14T20:31:40Z Indexed on 2010/04/14 20:33 UTC
Read the original article Hit count: 328

Filed under:
|

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 IS 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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about linq-to-sql