我首先使用c#中的存储库模式将asp.net 4.5与代码一起使用。
基类:
public interface IAuditableEntity
{
...
string DeletedBy { get; set; }
DateTime? DeletedDate { get; set; }
bool IsDeleted { get; set; }
}
public abstract class AuditableEntity: IAuditableEntity
{
...
public string DeletedBy { get; set; }
public DateTime? DeletedDate { get; set; }
public bool IsDeleted { get;set; }
}
class:
public class Group : AuditableEntity
{
public int Id {get;set;}
public string Code { get; set; }
public string Name { get; set; }
public GroupType Type { get; set; }
public string Description { get; set; }
public int? ParentId { get; set; }
}
Repository Base:
public class RepositoryBase<T> : IRepository<T> where T : class
{
protected DbContext _entities;
protected DbSet<T> dbSet;
#endregion
public RepositoryBase(DbContext context)
{
_entities = context;
dbSet = context.Set<T>();
}
...
public virtual IQueryable<T> GetAll()
{
try
{
return dbSet;
}
catch (Exception ex)
{
throw ex;
}
}
public virtual IQueryable<T> GetMany(Expression<Func<T, bool>> where)
{
return dbSet.Where(where);
}
...
}
我的问题:如果Repositorybase T使用GetAll
like:
GetMany
和IAuditableEntry
函数中添加表达式public virtual IQueryable<T> GetAll()
{
try
{
return dbSet.Where(x=> x is IAuditableEntity && !((IAuditableEntity)x).IsDeleted);
}
catch (Exception ex)
{
throw ex;
}
}
当我使用这个返回dbSet.Where(x => x是IAuditableEntity &&!((IAuditableEntity)x).IsDeleted);
它显示错误,如:
带有输入类型的'TypeIs'表达式“组”和类型检查不支持“ Base.IAuditableEntity”。唯一实体LINQ to Entities查询中支持类型和复杂类型。
您可以使用Expression<Func<T, bool>
,设置为参数类型。
通话:-
RepositoryClass.GetAll<EntityClassName>(x=> !((IAuditableEntity)x).IsDeleted)
GetALL方法调用:-
public virtual IQueryable<T> GetAll(Expression<Func<T, bool> exp) where T: IAuditableEntity
{
try
{
return dbSet.Where(exp)
}
catch (Exception ex)
{
throw ex;
}
}