asp.net 通用存储库由 属性 查找

asp.net Generic repository find by property

我在 ASP.NET 中使用通用存储库。现在我试图通过用户 ID 找到一个对象,该对象需要访问 class 的 属性,但是当然在 linq 表达式中 属性 是不知道的,因为它不知道知道类型了。有什么解决办法吗?

public virtual IEnumerable<T> GetByUser(string userId)
    {
        if (typeof(T).GetProperty("Employee") != null)
        {
            return Db.Set<T>().Where(x => x.Employee.Id == userId);
        }
        return new List<T>();
    }

"x.Employee.Id" 得到没有定义 Employee 的错误。这是可以预料的。我是否需要以完全不同的方式执行此操作,或者有人知道如何解决这个问题吗?

希望大家帮帮忙!

使用接口让您知道 T 将具有某些属性。或者使用基类型,然后对泛型参数使用约束。

public virtual IEnumerable<T> GetByUser(string userId) where T : IEmployee
{
   return Db.Set<T>().Where(x => x.Employee.Id == userId);
}

IEmployee 看起来像这样

public interface IEmployee 
{
    Employee Employee { get; set; }
}

显然这有点粗糙,但根据您的实体,这可能是一种方法。您总是可以映射出所有内容,然后为共享属性等构建接口。

不过老实说,我认为最好的方法是拥有一组功能更强大的通用存储库。例如一个基础仓库,然后是一个知道 T 将成为员工的 EmployeeRepostiory

MSDN Article on Constraints