【问题标题】:Want to select specific column through AutoMapper想通过 AutoMapper 选择特定的列
【发布时间】:2019-08-17 10:41:22
【问题描述】:

假设我们有一个带有以下声明的用户实体:

public class User
{
public string About { get; set; }
public string FirstName { get; set; }
public int Id { get; set; }
public string LastName { get; set; }
public string ProfileImageUrl { get; set; }
}

配置 AutoMapper:

using AutoMapper;
// ...
Mapper.CreateMap<User, UserSummary>();

由于两个类的属性名匹配,所以不需要进一步配置。

现在我正在转换这个查询

using (var context = new ApplicationContext())
{
var users = context.Users.ToList();
}

使用自动映射器,它的工作完美。

using AutoMapper.QueryableExtensions;
using System.Linq;
using (var context = new ApplicationContext())
{
var users = context.Users
                    .Project()
                    .To<UserSummary>()
                    .ToList();
}

生成的 SQL 查询是:

SELECT
[Extent1].[Id] AS [Id],
[Extent1].[About] AS [About],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[ProfileImageUrl] AS [ProfileImageUrl]
FROM [dbo].[Users] AS [Extent1]
go

现在如何使用自动映射器选择特定列而不是所有列?

我可以这样做,但它没有意义。

using (var context = new ApplicationContext())
{
 var users = context.Users
                    .Select(u => new UserSummary
                    {
                        FirstName = u.FirstName,
                        LastName = u.LastName,
                        ProfileImageUrl = u.ProfileImageUrl
                    })
                    .ToList();

}

提前谢谢你!

【问题讨论】:

  • MapFrom 没用。但是请检查the docs

标签: c# linq-to-entities automapper-6


【解决方案1】:

如果 StateName 是 StateMaster 和 StateMasterDTO 类中的属性名称,则不需要 .ForMember(),因为 AutoMapper 足够智能,可以自动映射它。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多