我可以找到数百个如何构建OData API的示例,但我正在使用OData API。
目前我们正在做一些可怕的事情,比如;
string filter = "FirstName eq '" + firstName + "' " +
"LastName eq '" + lastName + "'";但我假设有一个图书馆,我可以使用和做类似的事情;
SomeType query = new SomeType();
query.AddFitler("FirstName", Comparison.Equals, firstName);
query.AddFilter("LastName", Comparison.Equals, lastName);
string filter = query.ToString();你能帮我指出正确的方向吗-谢谢!
发布于 2020-12-29 16:03:18
我想我在搜索Strong-typed Linq to construct OData query options半天之后找到了解决方案
// url doesn't matter unless you will use data service to execute the call
var dsContext = new DataServiceContext(new Uri("http://stackoverflow"));
// need to pass in the controller into CreateQuery - could create an extension method to pluralize the type to not have to pass it in.
var query = dsContext.CreateQuery<Product>("/api/products").Where(p => p.Category == "Cars");
// ToString will output the url
var uri = new Uri(query.ToString());
// Grab just the path and query
var path = new Uri(uri.PathAndQuery, UriKind.RelativeOrAbsolute);
await client.GetAsync(path); // this will call the api not DataServiceContext现在只是测试!
编辑这个效果很好--我最后创建了一个小包装器来擦干它;
public class SearchQueryBuilderService<T>
{
private DataServiceContext _context = new DataServiceContext(new Uri("https://tickett.net"));
public string Build(Expression<Func<T, bool>> predicate)
{
return _context.CreateQuery<T>("tel").Where(predicate).ToString().Replace("https://tickett.net/tel?$filter=", "");
}
}因此,我现在可以从各种"Api存储库“中将其称为”Api存储库“;
string searchString = new SearchQueryBuilderService<SomePoco>().Build(sp => sp.SomeProp == "SomeValue");https://stackoverflow.com/questions/65491222
复制相似问题