I have a table in MySql and it contains 10 columns. I am implementing get API to fetch the data based on filter in query prams.
For example:
Select Data
From myTable
Where id = 2
and eId = 6
or
Select Data
From myTable
Where id = 2
and rlNumber = 6
and version = 8
I have following approaches:-
Where
clause based on pass parameters). We should avoid reflection.FilterType
and create a dictionary. Key will be enum and value will be where condition.Any better approach?
you can use the Specification Pattern:
interface ISpecification<T>
{
Expression<Func<T, bool>> ToLinq();
}
class AndSpecification<T> : ISpecification<T>
{
Specification left, right;
public Expression<Func<T,bool>> ToLinq() {
//merge left and right with an and
}
} //same for OrSpecification and NotSpecification
class VersionSpecification implements ISpecification<AModel> {
int version;
public Expression<Func<AModel, bool>> ToLinq() {
return x => x.Version == version
}
}
and then pass the specification from the business layer. The business layer doesn't know how specifications are implemented (Version can become Version2 and your business layer still works, you just have to change the specification) and your data access layer just have to accept a generic Specificiation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.