[英]Conflict OData with Repository pattern
I have method GetByID
in my repository that return generic type: 我的存储库中有方法
GetByID
返回通用类型:
public T GetById(object id)
{
return this.Entities.Find(id);
}
I'm going to use OData to filtering data, and for that (when I'm using $expand
for single row) I need to something like: 我将使用OData过滤数据,为此(当我将
$expand
用于单行时),我需要执行以下操作:
SingleResult.Create(repository.GetByID(id));
But of course I got error, because for SingleResult
needs type IQueryable<T>
. 但是我当然会出错,因为对于
SingleResult
需要键入IQueryable<T>
。
How can I implement it? 我该如何实施?
One bad solution is change my GetByID
to: 一个不好的解决方案是将我的
GetByID
更改为:
public IQueryable<T> GetById(object id)
{
return this.Entities.FirstOrDefault(p => p.ID == (int)id);
}
But I prefer to use T GetById
because in my opinion it is more correct. 但是我更喜欢使用
T GetById
因为我认为它更正确。
What type should return GetByID
? 什么类型应该返回
GetByID
? Could you please advise me what to do? 您能告诉我该怎么办吗?
The IQueryable interface defers the filtering to the caller which can do further filtering before "rendering" the final list (in Entity Framework it means executing the actual query with all the WHERE parameters applied at once). IQueryable接口将筛选推迟到调用方,后者可以在“呈现”最终列表之前进行进一步的筛选(在Entity Framework中,这意味着一次应用所有WHERE参数执行实际查询)。
So SingleResult needs an IQueryable to add any further filtering. 因此,SingleResult需要一个IQueryable来添加任何进一步的过滤。
If this.Entities is an EF collection (DBSet), you can use .Where(o => o.Id == id) which will return an IQueryable object. 如果this.Entities是EF集合(DBSet),则可以使用.Where(o => o.Id == id),它将返回IQueryable对象。
Your question is more one of design if it is good practice to have the Repository class return an IQueryable. 如果让Repository类返回IQueryable是一种好的做法,那么您的问题更多是设计问题。 I would say it depends on the general design of your solution and which responsibility you assign to which layer.
我要说的是,这取决于解决方案的总体设计以及要分配给哪一层的责任。
By looking at this answer ( OData $expand, DTOs, and Entity Framework ), if ODataController is expecting a IQueryable return type for [Queryable] methods then it is perfectly fine for the repository to return an IQueryable. 通过查看此答案( OData $ expand,DTO和Entity Framework ),如果ODataController期望[Queryable]方法的IQueryable返回类型,则存储库返回IQueryable很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.