Using Linq, trying to select all records not in my local set fails:
var localset = new List<Category>();
localset.Add( new Category { pk1 = 1, pk2 = 1, name = "one" } );
localset.Add( new Category { pk1 = 1, pk2 = 2, name = "two" } );
var dbCategories = dc.Categories;
var diff = dbCategories.Except(localset);
I need to do basic CRUD: delete from the db set when not in my local set, update where exists, and add new when not there.
I would normally do:
delete from Category C where not exists
( select null from LocalSet L where C.pk1 = L.pk1 and C.pk2 = L.pk2 )
update Category set name = L.name
from LocalSet L
where L.pk1 = Category.pk1 and L.pk2 = Category.pk2
insert into Category (pk1, pk2, name)
select pk1, pk2, name
from LocalSet L
where not exists (
select null from Category C where L.pk1 = C.pk1 and L.pk2 = C.pk2 )
Easy enough I thought. However, .Contains seems to be the only method that works with local sets, and it only seems to compare a single field. The database table has composite keys.
Without changing the composite keys, is there any way to accomplish these tasks?
You’ll have to implement a
CategoryComparerlike the following:Then call Enumerable.Except:
Let me know if this gets you what you need.