I have a reoccuring code block in my EntityFramework backed repository which I would like to genericise somehow and call as a method, so reuse the code rather than repeat it.
The current code block looks like this:
// Archive deleted MyItems sections
_t.MyItems.Where(x => x.ValidTo == null && !team.MyItems.Contains(x)).ToList().ForEach(x => x.ValidTo = DateTime.Now);
// Add or update MyItems sections
foreach (var MyItemsSection in team.MyItems)
{
if (MyItemsSection.Id == default(int))
{
MyItemsSection.ValidFrom = DateTime.Now;
_t.MyItems.Add(MyItemsSection);
}
else
{
var _MyItemsSection = _t.MyItems.FirstOrDefault(x => x.Id == MyItemsSection.Id);
context.Entry(_MyItemsSection).CurrentValues.SetValues(MyItemsSection);
}
}
_t is the EntityFramework connected object graph, while team is an identical type of object graph that has been disconnected and possibly updated externally. The goal here is to sync the two object graphs so the changes are persisted.
I need to pass in _t.MyItems and team.MyItems, where MyItems are to be genericised so the same method works for MyOtherItems and MySocks, MyUnderPants etc.
Is this at all possible?
In answer to my own question, here is the answer – what I was missing was the fact that you can require the incoming type as implementing a specific interface, and still have it available as the type wanted.
So, here is what I came up with:
The part which I was looking for was the
where TEntity : class, IEntityIn this solution, I have to make sure that my entities implement the interface IEntity, which simply is:
This allows the compiler to quit complaining about the use of those properties, while I can still use the actual type so Entity Framework is also satisfied and left less confused about whats going on.
Hope this helps someone else.