我使用 Entity Framework 作为我的 ORM,我的每个类都实现了一个接口(interface),该接口(interface)基本上表示表结构(每个字段一个只读属性)。这些接口(interface)旨在在不同应用程序的程序集之间共享。它们不支持任何写入操作。
现在 EF 允许我使用 IQueryable
的实例。我想要的是对 IQueryable
的支持,它将在它之上。不用说,我希望能够使用接口(interface)属性执行 Where 操作。
这是否可行,还是我在这里浪费时间?我尝试实现自己的 IQueryProvider 和 ExpressionVisitor,但到目前为止效果并不好。我对 LINQ 的表达式结构几乎没有经验。这是要走的路还是有另一种更好的方法?
我可能不完全理解你想用这个做什么,但我看到的常用方法(我自己也已经采用)是使用泛型创建一个存储库。如果为泛型设置约束,则可以使用实体接口(interface)的属性。像这样的东西...
public interface IRepository
where T : class, IEntityInterface
{
T FindById(int id);
IQueryable All { get; }
}
public class GenericRepository : IRepository
where T : class, IEntityInterface
{
public T FindById(int id)
{
//Uses the Id property from the interface
return All.Where(t => t.Id == id).Single();
}
public IQueryable All
{
get
{
//Get DbContext instance from somewhere
return _dbContext.Set();
}
}
}
public interface IEntityInterface
{
int Id { get; }
}
然后,您可以通过使实体接口(interface)也成为泛型类型来进一步了解泛型。这一切都与依赖注入(inject)和/或工厂模式(如果你喜欢的话)配合得很好。
Tôi là một lập trình viên xuất sắc, rất giỏi!