我在管理器類中實作 Get 方法存在問題。我需要如何過濾以及需要在哪里撰寫過濾方法。
簡而言之 - 我有資料類 Gym、存盤庫類和方法 Find。我在資料類中撰寫了方法 - IsAppreciateToRequest(RequestName) 在管理器類中做這樣的事情
public IEnumerable<GymDto> GetGyms(GetGymRequest request)
{
return _gymRepository
.Find(gym => gym.IsAppreciateToRequest(request))
.AsEnumerable()
.Select(GymDto.FromEntityToDto);
}
我認為這是狗屎代碼,但也知道如何擺脫它以及如何以正確的方式撰寫它(在此之前,我在每個管理器類中都有 30-50 行之類的 ??Get 方法)
IsAppreciateToRequest 方法:
public bool IsAppreciateToRequest(GetGymRequest other)
{
return (string.IsNullOrEmpty(other.Name) || Name == other.Name)
&& (string.IsNullOrEmpty(other.Location) || Location == other.Location)
&& (other.SectionRequest == null || Sections.All(section => section.IsAppreciateToRequest(other.SectionRequest)));
}
uj5u.com熱心網友回復:
您可以使用LINQKit將運算式樹注入過濾器。需要配置DbContextOptions:
builder
.UseSqlServer(connectionString) // or any other provider
.WithExpressionExpanding(); // enabling LINQKit extension
您的類應該使用回傳的靜態函式進行擴展,Expression<Func<>>并且當前方法應該具有ExpandableAttribute
例如:
public class Gym
{
[Expandable(nameof(IsAppreciateToRequestImpl))]
public bool IsAppreciateToRequest(GetGymRequest other)
{
return (string.IsNullOrEmpty(other.Name) || Name == other.Name)
&& (string.IsNullOrEmpty(other.Location) || Location == other.Location)
&& (other.SectionRequest == null || Sections.All(section => section.IsAppreciateToRequest(other.SectionRequest)));
}
private static Expression<Func<Gym, GetGymRequest, bool>> IsAppreciateToRequestImpl()
{
// first parameter is current object
return (gym, other) => (string.IsNullOrEmpty(other.Name) || gym.Name == other.Name)
&& (string.IsNullOrEmpty(other.Location) || gym.Location == other.Location)
&& (other.SectionRequest == null || gym.Sections.All(section => section.IsAppreciateToRequest(other.SectionRequest)));
}
}
// the same technique as in Gym class
public class Section
{
[Expandable(nameof(IsAppreciateToRequestImpl))]
public bool IsAppreciateToRequest(GetSectionRequest other)
{
return // unknown;
}
private static Expression<Func<Section, GetSectionRequest, bool>> IsAppreciateToRequestImpl()
{
// first parameter is current object
return (section, other) => // unknown;
}
}
然后 LINQKit 將擴展靜態方法回傳的運算式,并將條件注入謂詞。
相同的方法可用于將物體投影到 DTO。與我在這里的回答類似,它也顯示了 LINQKit 的已知替代方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/494225.html
標籤:C# 林克 asp.net-web-api
