我热衷于使用ServiceStack,并创建了一个带有简单客户服务的小测试应用程序:
[Route("/customers/{id}")]
public class GetCustomer : IReturn<Customer>
{
public int Id { get; set; }
}
[Route("/customers/search")]
public class FindCustomers : IReturn<List<Customer>>
{
public string LastName { get; set; }
public int Age { get; set; }
public string? City { get; set; }
}
public class CustomerService : IService
{
public object Get(GetCustomer request)
{
var db = new WebServDb();
var customer = db.FirstOrDefault<Customer>("WHERE Id=@0", request.Id);
return customer;
}
public object Get(FindCustomers request)
{
var db = new WebServDb();
var customers = new List<Customer>();
if (request.City.HasValue)
customers = db.Fetch<Customer>("WHERE LastName=@0 AND Age=@1 AND City=@2", request.LastName, request.Age, request.City);
else
customers = db.Fetch<Customer>("WHERE LastName=@0 AND Age=@1", request.LastName, request.Age);
return customers;
}
}
FindCustomers请求 DTO 包含 3个可用于搜索客户的属性。根据设置的属性,我需要以不同的方式查询数据库。那么最好的方法是什么?例如,如果我添加另一个属性,例如:
[Route("/customers/search")]
public class FindCustomers : IReturn<List<Customer>>
{
public string LastName { get; set; }
public int Age { get; set; }
public string? City { get; set; }
public string? ZipCode { get; set; }
}
对于FindCustomers DTO,我还必须将服务Get方法更改为:
public object Get(FindCustomers request)
{
var db = new WebServDb();
var customers = new List<Customer>();
if (request.City.HasValue && request.ZipCode.HasValue)
customers = db.Fetch<Customer>("WHERE LastName=@0 AND Age=@1 AND City=@2 AND ZipCode=@3", request.LastName, request.Age, request.City, request.ZipCode);
else if (request.City.HasValue)
customers = db.Fetch<Customer>("WHERE LastName=@0 AND Age=@1 AND City=@2", request.LastName, request.Age, request.City);
else
customers = db.Fetch<Customer>("WHERE LastName=@0 AND Age=@1", request.LastName, request.Age);
return customers;
}
因此,对于我从请求 DTO 添加/删除的每个属性,我需要修改我的Get方法。有更好的方法吗?检查属性集和查询数据库的更通用方法?
在CustomerService中有特定的请求 DTO(例如FindCustomersByLastNameCity、FindCustomersByLastNameZipCode等)以及相应的特定 Get 方法会更好吗?