I have an abstract class called Fruit. Then I got an Apple derived class .
I have two extension methods:
public static IQueryable<TFruit> WithEagerLoading<TFruit>(this IQueryable<TFruit> query) where TFruit : Fruit
{
return query.EagerLoad(x => x.Distributors);
}
public static IQueryable<Apple> WithEagerLoading(this IQueryable<Apple> query)
{
query = query.EagerLoad(x => x.AppleBrands);
return query.WithEagerLoading<Apple>();
}
Now, here is the general method that I have in the repository:
public TFruit FindById<TFruit>(int fruitId) where TFruit : Fruit
{
var query = _ctx.Fruits
.OfType<TFruit>();
query = query.WithEagerLoading();
return query.SingleOrDefault(x => x.FruitId == fruitId);
}
I have a problem when I do this:
var apple = repository.FindById<Apple>(1);
It goes into the extension method IQueryable<Fruit>.
I want it to be part of the extension method IQueryable<Apple>. For other types of fruit, it should go into the extension method IQueryable<TFruit>.
I thought the compiler would choose the most specific extension method.
Any ideas?
EDIT
Thanks for the comments / response. Now I see why this does not work.
So what are the options to solve this problem? If I create a method:
public static IQueryable<Apple> WithAppleEagerLoading(this IQueryable<Apple> query)
? TFruit:
public TFruit FindById<TFruit>(int fruitId) where TFruit : Fruit
{
var query = _ctx.Fruits
.OfType<TFruit>();
if (typeof(TFruit) == typeof(Apple))
query = query.WithAppleEagerLoading();
else
query = query.WithEagerLoading();
return query.SingleOrDefault(x => x.FruitId == fruitId);
}
- , 20 .
- , ?