投实体到实现的接口为实体框架泛型方法使用LINQ [英] Cast Entity to Implemented Interface in a Generic Method Using LINQ for Entity Framework
问题描述
我有一个通用的方法来查询EF型TEntity的对象。我想补充一个条件为WHERE子句如果TEntity实现一个特定的接口。我的方法是:
I have a generic method to query objects of type TEntity in EF. I Want to add a condition as a where clause if TEntity implements a specific interface. The method I have is:
public TEntity GetByUserID(Guid userID)
{
var query = this.DbSet;
if (typeof (TEntity).IsImplementationOf<IDeletableEntity>())
{
query = query
.Where((x => !((IDeletableEntity)x).IsDeleted);
}
return query
.FirstOrDefault(x => x.UserID == userID);
}
IsImplementationOf&下;>()是方法顾名思义刚刚返回真/假
IsImplementationOf<>() is method which just returns true/false as the name implies.
。当我运行这为它们实现IDeletableEntity实体地址,我得到一个错误:
When I run this for the entity Address which implement IDeletableEntity, I get an error:
无法转换的类型地址键入 IDeletableEntity。LINQ到实体仅支持铸造EDM原始或枚举类型。
Unable to cast the type 'Address' to type 'IDeletableEntity'. LINQ to Entities only supports casting EDM primitive or enumeration types.
任何想法我怎么能去解决此限制LINQ的?
Any ideas how I can go around this limitation of LINQ?
推荐答案
这是一个可行的解决方案:
This is a working solution:
public TEntity GetByUserID(Guid userID, params Include<TEntity>[] includes)
{
var query = this.DbSet;
query = Where<IDeletableEntity>(query, x => !x.IsDeleted);
return query
.FirstOrDefault(x => x.UserID == userID);
}
public static IQueryable<TEntity> Where<TPredicateWellKnownType>(IQueryable<TEntity> query, Expression<Func<TPredicateWellKnownType, bool>> predicate)
{
if (typeof(TEntity).IsImplementationOf<TPredicateWellKnownType>())
{
query = ((IQueryable<TPredicateWellKnownType>)query)
.Where(predicate)
.Cast<TEntity>();
}
return query;
}
这篇关于投实体到实现的接口为实体框架泛型方法使用LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!