Cast Entity to Implemented Interface in a Generic Method Using LINQ for Entity Framework

前端 未结 3 1762
滥情空心
滥情空心 2020-12-10 04:19

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:

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 04:56

    This is a working solution:

    public TEntity GetByUserID(Guid userID, params Include[] includes)
    {
        var query = this.DbSet;
        query = Where(query, x => !x.IsDeleted);
        return query
            .FirstOrDefault(x => x.UserID == userID);
    }
    
    public static IQueryable Where(IQueryable query, Expression> predicate)
    {
        if (typeof(TEntity).IsImplementationOf())
        {
            query = ((IQueryable)query)
                .Where(predicate)
                .Cast();
        }
        return query;
    }
    

提交回复
热议问题