Generic Any/Attach/Add function for Entity Framework
- by Matt Thrower
Looking through my EF classes, they're littered with code that looks like this:
if (_myContext.[EntityType].Any(d => d.RowId == dc.RowId))
{
_myContext.[EntityType].Attach(dc);
_myContext.Entry(dc).State = EntityState.Modified;
}
else
{
_myContext.[EntityType].Add(dc);
}
It's the same thing over and over, and is clearly itching to be handled by a generic function.
However, I'm not sure how you'd go about handling the need for it to deal with a variety of unexpected entity types. A good example to get me started would be most appreciated.