I currently have a complete generic repository but I’m missing one feature and that is to use
Include() and Find() together.
So now I have:
public E FindById<E>(int id) where E : class
{
return DataContext.Set<E>().Find(id);
}
called using
var person = PersonRepo.FindById<Person>(personId);
I would like to have something similar to:
var person = PersonRepo.FindByIdWithIncludes<Person>(personId,new[]{"State.Address"});
So, something along this lines (this is only a test):
public E FindByIdWithIncludes<E>(int id, string[] includes) where E : class
{
var entitySet = DataContext.Set<E>();
DbQuery<E> entityQuery;
foreach (var include in includes)
{
entityQuery = entitySet.Include(include);
}
return entityQuery.Find(id); //this is were it breaks
}
Is it possible?
You cannot use
Finddirectly –Finddoesn’t work with includes. You must useSingleOrDefault.First you need to define interface for your entities to expose their key.
Next you can write simple method with constrain to get access to the key:
Btw. you can use strongly typed includes – here is an example.