[英]Net Core: Using OData in Onion Architecture, Convert Query Parameters Into Linq
我們正在創建搜索 Function 以返回大型數據庫中的匹配地址記錄。
地址表包含 SQL 表中的 20+ 列,需要使用不同的 OData 參數進行查詢,(EqualTo、Contains、Starts With 等)。
嘗試使用 OData,而不將 DBContext 注入 API Controller。 這在當前架構中是不允許的。 如何編寫代碼來實現這一點?
*我們使用 ProjectTo 讓它工作。 但是 OData Http 特定功能正在傳遞到非 Api 級別。 目前在 AppServices 中有 ODataQueryOptions。
我們如何將整個 ODataQueryOptions 轉換為 Linq 表達式查詢(無論傳入什么),此資源僅用於過濾器, 如何將 OData 過濾器轉換為 LINQ 表達式?
DBContext-->DomainLayer-->Dto-->然后是API級別,
中間的兩層。 映射器 map 從 EF DBContext 到 Domain 到 Dto。
存儲庫方法帶來數據。
AppService 方法轉換為 Dto。
ProjectTo 的當前解決方案:
Controller API:
[HttpGet]
public async Task<ActionResult<IList<AddressTypeDto>> GetAddressAPI(ODataQueryOptions<AddressTypeDto> queryOptions)
{
return Ok(await _service.GetAddressTypeDto(queryOptions));
}
申請服務:
(我們如何在 Startup 中應用 ODataModelBuilder 映射?)
public async Task<AddressTypeResponse> GetAddressTypeDto(ODataQueryOptions<AddressTypeDto> queryOptions)
{
var dto = (IQueryable<AddressTypeDto>)queryOptions.ApplyTo(_addressRepository.GetAddressTypes().ProjectTo<AddressTypeDto>(_mapper.ConfigurationProvider));
var dtoList = await dto.ToListAsync();
return dto;
}
存儲庫:
[EnableQuery]
public IQueryable<LkAddressType> GetAddressTypesData()
{
return _ctx.LkAddressType.AsNoTracking();
}
課程:
public class AddressTypeDto
{
public int AddressTypeId { get; set; }
public int? LastModifiedByUserId { get; set; }
public string AddressTypeCode { get; set; }
public string AddressTypeDescription { get; set; }
public bool? Status { get; set; }
public DateTime? CreateDate { get; set; }
}
public LkAddressType()
{
public int LkAddressTypeId { get; set; }
public int? LastModifiedByUserId { get; set; }
public string AddressTypeCode { get; set; }
public string AddressTypeDescription { get; set; }
public bool? Status { get; set; }
public DateTime? CreateDate { get; set; }
public DateTime? EffectiveStartDate { get; set; }
public DateTime? EffectiveEndDate { get; set; }
}
使用 C# Net Core 2.2,實體框架,Sql 服務器數據庫
資源:也試圖利用這個
自從我寫這個 function 以來已經有很長時間了,但這些鏈接可能會有所幫助。 GetAll() 只返回一個 IEnumerable。
[Route(""), HttpGet]
public IHttpActionResult Get(ODataQueryOptions<Language> queryOptions)
{
Log.Info($"{nameof(Get)} (ODataQueryOptions)");
//OData directly with normal WebAPI
//https://blogs.msdn.microsoft.com/webdev/2013/02/25/translating-odata-queries-to-hql/
//https://stackoverflow.com/questions/10781309/asp-net-mvc-4-webapi-manually-handle-odata-queries
//https://blogs.msdn.microsoft.com/odatateam/2014/07/04/tutorial-sample-using-odatauriparser-for-odata-v4/
//OData without entity framework, but full-on odata controller
//http://www.odata.org/blog/how-to-use-web-api-odata-to-build-an-odata-v4-service-without-entity-framework/
//OData tips and tricks
//https://blogs.msdn.microsoft.com/davidhardin/2014/12/17/web-api-odata-v4-lessons-learned/
return Ok(queryOptions.ApplyTo(_repository.GetAll().AsQueryable()));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.