如何将实体框架包含扩展方法引入通用IQueryable< TSource>。 [英] How to brings the Entity Framework Include extention method to a Generic IQueryable<TSource>
问题描述
这是东西。
我有一个接口,我想使用 Include
扩展方法,谁属于 EntityFramework 库,属于我的 IRepository
层,而无需了解 EntityFramework 。
I have an interface, and I would to put the Include
extension method, who belongs to EntityFramework library, to my IRepository
layer wich dont needs to knows about EntityFramework.
public interface IRepository<TEntity>
{
IQueryable<TEntity> Entities { get; }
TEntity GetById(long id);
TEntity Insert(TEntity entity);
void Update(TEntity entity);
void Delete(TEntity entity);
void Delete(long id);
}
所以我有扩展方法:
public static class IncludeExtension
{
static IQueryable<TEntity> Include<TEntity>(this IQueryable<TEntity> query,
string path)
{
throw new NotImplementedException();
}
}
但是我不知道如何实现此层,然后将其发送到我的EntityFramework(或将实现IRepository的任何人)进行处理。
But I don't know how to implement it in this layer, and I would to send it to my EntityFramework (or whatever who will implement the IRepository) to deal with.
我需要使用扩展方法对接口进行相同处理。
I need same to a Interface with a extension method.
有光吗?
推荐答案
这个问题有点老了,但是,如果您或其他任何人仍在寻找,则有两种独立于EF的解决方案:
This question is a bit old, but here are two EF-independent solutions if you or anyone else is still looking:
1。基于反射的解决方案
如果 IQueryable
,则.NET Framework只能使用此解决方案不会转换为 DbQuery
或 ObjectQuery
。跳过这些强制转换(及其提供的效率),即可将解决方案与Entity Framework分离。
This solution is what the .NET Framework falls back to if the IQueryable
does not cast to a DbQuery
or ObjectQuery
. Skip these casts (and the efficiency it provides) and you've decoupled the solution from Entity Framework.
public static class IncludeExtension
{
private static T QueryInclude<T>(T query, string path)
{
MethodInfo includeMethod = query.GetType().GetMethod("Include", new Type[] { typeof(string) });
if ((includeMethod != null) && typeof(T).IsAssignableFrom(includeMethod.ReturnType))
{
return (T)includeMethod.Invoke(query, new object[] { path });
}
return query;
}
public static IQueryable<T> Include<T>(this IQueryable<T> query, string path) where T : class
{
return QueryInclude(query, path);
}
// Add other Include overloads.
}
2。基于Dyanmics的解决方案
此处, QueryInclude< T>
方法使用动态
类型以避免反射。
Here the QueryInclude<T>
method uses the dynamic
type to avoid reflection.
public static class IncludeExtension
{
private static T QueryInclude<T>(T query, string path)
{
dynamic querytWithIncludeMethod = query as dynamic;
try
{
return (T)querytWithIncludeMethod.Include(path);
}
catch (RuntimeBinderException)
{
return query;
}
}
public static IQueryable<T> Include<T>(this IQueryable<T> query, string path) where T : class
{
return QueryInclude(query, path);
}
// Add other Include overloads.
}
这篇关于如何将实体框架包含扩展方法引入通用IQueryable< TSource>。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!