将非集合子实体有效映射到 Entity Framework Core 中的 DTO
Entity Framework Core 使用表达式树简化了实体到 DTO(数据传输对象)的转换。 这对于父对象和子集合很有效,但处理非集合子属性需要不同的方法。
挑战:
考虑这个模型:
<code class="language-csharp">public class Model { public int ModelId { get; set; } public string ModelName { get; set; } public virtual ICollection<ChildModel> ChildModels { get; set; } public AnotherChildModel AnotherChildModel { get; set; } }</code>
使用像这样的简单表达式直接映射到 DTO 会失败 AnotherChildModel
:
<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 mapping missing };</code>
解决方案:利用外部库
一些库扩展了表达式树功能来处理这种情况:
Expandable
属性来标记查询提供程序扩展的方法。<code class="language-csharp">[Expandable(nameof(AsDtoImpl))] public static ModelDto AsDto(Model model) => AsDtoImpl.Compile()(model); private static readonly Expression<Func<Model, ModelDto>> AsDtoImpl = 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>
在查询中使用.AsExpandable()
:
<code class="language-csharp">dbContext.Models .Where(m => SomeCriteria) .Select(Model.AsDto) .AsExpandable() .ToList();</code>
InjectLambda
属性。<code class="language-csharp">[InjectLambda] public static ModelDto AsDto(Model model) { /* ... same implementation as LINQKit ... */ }</code>
在查询中使用.ToInjectable()
:
<code class="language-csharp">dbContext.Models .Where(m => SomeCriteria) .Select(Model.AsDto) .ToInjectable() .ToList();</code>
Computed
属性提供更简单的语法。<code class="language-csharp">[Computed] public static ModelDto AsDto(Model model) { /* ... same implementation as LINQKit ... */ }</code>
在查询中使用.Decompile()
:
<code class="language-csharp">dbContext.Models .Where(m => SomeCriteria) .Select(Model.AsDto) .Decompile() .ToList();</code>
这些库提供了将非集合子实体映射到 Entity Framework Core 查询中的 DTO 的有效解决方案,避免了基本表达式树映射的限制。 选择最适合您的项目需求和编码风格的库。
以上是如何在 Entity Framework Core 中高效地将非集合子实体转换为 DTO?的详细内容。更多信息请关注PHP中文网其他相关文章!