gpt4 book ai didi

.net - 包装 IQueryable

转载 作者:行者123 更新时间:2023-11-30 23:50:23 27 4
gpt4 key购买 nike

我使用 Entity Framework 作为我的 ORM,我的每个类都实现了一个接口(interface),该接口(interface)基本上表示表结构(每个字段一个只读属性)。这些接口(interface)旨在在不同应用程序的程序集之间共享。它们不支持任何写入操作。

现在 EF 允许我使用 IQueryable 的实例。我想要的是对 IQueryable 的支持,它将在它之上。不用说,我希望能够使用接口(interface)属性执行 Where 操作。

这是否可行,还是我在这里浪费时间?我尝试实现自己的 IQueryProvider 和 ExpressionVisitor,但到目前为止效果并不好。我对 LINQ 的表达式结构几乎没有经验。这是要走的路还是有另一种更好的方法?

最佳答案

我可能不完全理解你想用这个做什么,但我看到的常用方法(我自己也已经采用)是使用泛型创建一个存储库。如果为泛型设置约束,则可以使用实体接口(interface)的属性。像这样的东西...

public interface IRepository<T>
where T : class, IEntityInterface
{
T FindById(int id);
IQueryable<T> All { get; }
}

public class GenericRepository<T> : IRepository<T>
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<T> All
{
get
{
//Get DbContext instance from somewhere
return _dbContext.Set<T>();
}
}
}

public interface IEntityInterface
{
int Id { get; }
}

然后,您可以通过使实体接口(interface)也成为泛型类型来进一步了解泛型。这一切都与依赖注入(inject)和/或工厂模式(如果你喜欢的话)配合得很好。

关于.net - 包装 IQueryable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17558165/

27 4 0