Streamlining DTO Conversion for Non-Collection Child Properties in EF Core
Entity Framework Core (EF Core) simplifies entity-to-DTO (Data Transfer Object) conversion, especially for child collections. However, handling individual, non-collection child properties requires a more nuanced approach. Directly embedding the conversion logic within the expression, while functional, leads to code duplication.
Consider this example:
<code class="language-csharp">public static Expression<Func<Model, ModelDto>> AsDto => model => new ModelDto { ModelId = model.ModelId, ModelName = model.ModelName, ChildModels = model.ChildModels.AsQueryable().Select(ChildModel.AsDto).ToList(), AnotherChildModel = new AnotherChildModelDto { AnotherChildModelId = model.AnotherChildModel.AnotherChildModelId } };</code>
To avoid repetitive code, leveraging open-source libraries offers a more elegant solution. These libraries inject custom query providers into EF Core, enabling the manipulation of expression trees:
LINQKit: Utilizes the Expandable
attribute and AsExpandable
extension method to modify the expression tree.
<code class="language-csharp"> [Expandable(nameof(AsDtoImpl))] public static ModelDto AsDto(Model model) { _asDtoImpl ??= AsDtoImpl().Compile(); return _asDtoImpl(model); } private static Func<Model, ModelDto> _asDtoImpl; private static Expression<Func<Model, ModelDto>> AsDtoImpl => model => new ModelDto { ModelId = model.ModelId, ModelName = model.ModelName, ChildModels = model.ChildModels.AsQueryable().Select(ChildModel.AsDto).ToList(), AnotherChildModel = ChildModelToDto(model.AnotherChildModel) //Simplified call }; } private static AnotherChildModelDto ChildModelToDto(AnotherChildModel model) { return new AnotherChildModelDto { AnotherChildModelId = model.AnotherChildModelId }; }</code>
NeinLinq: Offers [InjectLambda]
and ToInjectable()
for injecting custom lambda expressions. The implementation is similar to LINQKit, substituting the attribute and method.
DelegateDecompiler: Employs the [Computed]
attribute for direct lambda-to-delegate translation. Again, the structure mirrors the LINQKit example, simplifying the call to a separate method for clarity.
By using these libraries, you can refactor the child property conversion into separate, reusable functions, significantly improving code maintainability and reducing redundancy. The custom query provider ensures correct evaluation of the modified expression trees within the EF Core context.
The above is the detailed content of How Can I Efficiently Convert Non-Collection Child Properties to DTOs in EF Core?. For more information, please follow other related articles on the PHP Chinese website!