【问题标题】:AutoMapper select expression translationAutoMapper 选择表达式翻译
【发布时间】:2018-06-10 21:20:34
【问题描述】:

我试图准确了解 AutoMapper 将为以下映射生成什么选择表达式。我正在尝试复制一个仅在使用 AutoMapper 投影时才会出现的错误,但不会使用手工选择表达式。我知道映射表达式是多余的,可能会被简化,但错误也会消失。

我相信映射应该逐字生成一个选择表达式,但我知道它不会,因为通过替换该表达式而不是使用 AutoMapper 进行投影,一切都按预期工作(并且错误消失了)。

dbContext.Blogs.Select(blog => new BlogDto { Post = blog.Posts.Any() ? blog.Posts.Select(post => new PostDto()).FirstOrDefault() : null })

public class Blog
{
    public Guid Id { get; set; }

    [InverseProperty(nameof(Post.Blog))]
    public virtual List<Post> Posts { get; } = new List<Post>();
}
public class Post
{
    public Guid Id { get; set; }
    public Guid BlogId { get; set; }

    [ForeignKey(nameof(BlogId))]
    public virtual Blog Blog { get; private set; }
}

public class BlogDto
{
    public PostDto Post { get; set; }
}
public class PostDto { }

public class BlogProfile : Profile
{
    public BlogProfile()
    {
        CreateMap<Blog, BlogDto>()
            .ForMember(x => x.Post, x => x.MapFrom(y => y.Posts.Any() ? y.Posts.FirstOrDefault() : null));
    }
}
public class PostProfile : Profile
{
    public PostProfile()
    {
        CreateMap<Post, PostDto>();
    }
}

TLDR 我试图了解选择表达式逐字 AutoMapper 将使用上述映射生成什么(或如何)。

【问题讨论】:

标签: c# automapper


【解决方案1】:

根据@LucianBargaoanu 的建议,为了获得AutoMapper 在使用ProjectTo&lt;&gt;() 时生成的精确select 表达式,您只需调用context.Entities.ProjectTo&lt;Dto&gt;().Expression.ToString()。表达式中有一个IIF 语句,我刚刚将它翻译成一个三元表达式。

对于发布的映射,ToString() 的输出如下。

value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[EFCoreBugs.Blog]).Select(dtoBlog => new BlogDto() {Post = IIF((IIF(dtoBlog.Posts.Any(), dtoBlog.Posts.FirstOrDefault(), null) == null), null, new PostDto() {})})

这将极大地帮助诊断/理解更复杂的查询表达式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2022-10-20
    相关资源
    最近更新 更多