首页 > 后端开发 > C++ > 如何在 Entity Framework Core 中高效地将非集合子实体转换为 DTO?

如何在 Entity Framework Core 中高效地将非集合子实体转换为 DTO?

Mary-Kate Olsen
发布: 2025-01-23 19:57:13
原创
862 人浏览过

将非集合子实体有效映射到 Entity Framework Core 中的 DTO

Entity Framework Core 使用表达式树简化了实体到 DTO(数据传输对象)的转换。 这对于父对象和子集合很有效,但处理非集合子属性需要不同的方法。

How to Efficiently Convert Non-Collection Child Entities to DTOs in Entity Framework Core?

挑战:

考虑这个模型:

<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>
登录后复制

解决方案:利用外部库

一些库扩展了表达式树功能来处理这种情况:

  • LINQKit: 使用 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>
登录后复制
  • NeinLinq: 与 LINQKit 类似,使用 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>
登录后复制
  • DelegateDecompiler: 使用 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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板