Search code examples
c#linqlinqpad

Update Multiple Records Based on Multi-column Key


I need to update multiple records based on a list of records to change. When that list is identified by one column, doing so is simple:

var fooIds = new List<int> { 2, 3, 4}
var foosToChange = Foo.Where(f => fooIds.Contains(f.Id));
// Update foosToChange and save here

What happens when the incoming list is an object with two properties that are needed to identity the record? For example:

var fooIds = new []
  {
    new { prop1 = "12345", prop2 = 2017111701 },
    new { prop1 = "hij", prop2 = 2018060101 }
  };

What would this need to become?

var foosToChange = Foo.Where(f => fooIds.Contains(???));

Is this even possible?


Solution

  • The query below will get the job done. If high performance is a must for the query, you could look into using a stored procedure with a Table Valued Parameter.

    var keys = fooIds.Select(f => f.prop1 + "." + f.prop2);
    
    Foo.Where(f => keys.Contains(f.prop1 + "." + f.prop2))