【发布时间】:2017-08-05 14:41:05
【问题描述】:
可能这是一个愚蠢的问题。
我在 Asp.Net web api 2.2 应用程序中有一些模型类,它实现了一个接口 ICountryOfOrigin。
我需要通过应用 where 子句来过滤记录,如下所示。我必须在许多具有不同模型的控制器中重复这个逻辑,这些控制器实现了ICountryOfOrigin。
是否可以将过滤逻辑移动到单独的方法中,并通过数据注释将其应用于控制器动作?
我的目的是消除重复代码。
有可能吗?
//Interface
public Interface ICountryOfOrigin
{
string Country {get;set;}
}
//Model
public class Product : ICountryOfOrigin
{
..
string Country {get;set;}
}
//Action
public IHttpActionResult Get()
{
List<string> euCountries = GetEuCountries();
Product product = _repository.Products.GetAll().Where(p=> euCountries.Contains(p.countries); // The filter is applied here
return Ok(products);
}
//Need to achieve something like this
[EuCountriesOnly]
public IHttpActionResult Get()
{
List<string> euCountries = GetEuCountries();
Product product = _repository.Products.GetAll();
return Ok(products);
}
有没有专家帮助我解决这个问题?
【问题讨论】:
-
“我必须在许多具有不同模型的控制器中重复这个逻辑,这些控制器实现了 ICountryOfOrigin。” - 那是因为你不应该访问控制器中的数据库,而是抽象的那。查看存储库模式。
-
@CodeCaster 是的,我正在使用通用存储库模式。我的问题是关于数据注释的。
-
从你的代码看不像。
-
@CodeCaster 这就是我从产品存储库中凝胶化产品的方式。
_repository.Products.GetAll();(我对上面的代码做了些微改动。)我的问题是我必须在许多控制器中重复_repository.Products.GetAll();。如何通过 DataAnnotations 应用 where 子句? -
@Nkosi 您能否通过代码示例提供答案;)?
标签: c# asp.net asp.net-web-api data-annotations