【问题标题】:Is it possible to set the where clause through a data annotation?是否可以通过数据注释设置 where 子句?
【发布时间】: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


【解决方案1】:

我想我会射杀任何按照你想要的方式实施它的人。相信我,用你放在调用方法上的属性来改变你正在调用的某些方法的行为一点都不酷。

只需将逻辑放入存储库类型的扩展方法中即可:

public static class RepoExtensions
{
  private static readonly euCountries = new Country[]{};
  public static IEnumerable<ICountryOfOrigin> GetEU(this Repository repo)
  {
    return repo.Products.GetAll().Where(p=> euCountries.Contains(p.countries);
  }
}

我假设您的存储库是 Repository 类型,您需要输入真实类型而不是它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    相关资源
    最近更新 更多