[英]How to generalize these linq queries
我有這個方法:
public IEnumerable<PackModel> PackLookup(short? society, string description)
{
return this.context.Pack.Where(x => x.Description.Contains(description) &&
(!society.HasValue || x.Society == society))
.OrderBy(x => x.Code)
.Take(this.max);
}
public IEnumerable<FeaturesModel> FeaturesLookup(short? society, string description)
{
return this.context.Features.Where(x => x.Description.Contains(description) &&
(!society.HasValue || x.Society == society))
.OrderBy(x => x.Code)
.Take(this.max);
}
public IEnumerable<ConstraintsModel> ConstraintsLookup(short? society, string description)
{
return this.context.Constraints.Where(x => x.Description.Contains(description) &&
(!society.HasValue || x.Society == society))
.OrderBy(x => x.Code)
.Take(this.max);
}
這三個方法非常相似,只是 DbSet 發生了變化,我怎樣才能以通用的方式進行這些調用以避免代碼重復
假設您的所有實體模型共享具有Description
、 Code
和Society
屬性的相同接口,那么您可以使用 DbContext 的Set<T>
方法和泛型類型約束進行抽象,例如:
public IEnumerable<TModel> Lookup<TModel>(short? society, string description)
where TModel : class, IYourInterface
{
return this.context.Set<TModel>()
.Where(x => x.Description.Contains(description) &&
(!society.HasValue || x.Society == society))
.OrderBy(x => x.Code)
.Take(this.max);
}
現在你這樣稱呼它:
var results = Lookup<PackModel>("society", "description");
var results = Lookup<FeaturesModel>("society", "description");
var results = Lookup<ConstraintsModel>("society", "description");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.