如何向 Automapper 发送额外数据

问题描述 投票:0回答:1

我们有一个实体类型类,当它转换为 dto 类时,我希望通过额外的计算来设置一个属性。实体类:

 public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string  LastName { get; set; }
    public byte Score { get; set; }
}

D 上课:

public class StudentRankingDto
{
        
    public int Id { get; set; }
    public string Name { get; set; }  // FirstName +" " +LastName
    public string Rank { get; set; }
}

在Dto类中,rank属性值是根据字典计算的。

词典:

 Dictionary<byte,string> Ranks { get; set; } = new Dictionary<byte, string>() 
{
    {0,"rejected" },
    {1,"very weak" },
    {2,"very weak" },
    {3,"weak" },
    {4,"weak" },
    {5,"medium" },
    {6,"medium" },
    {7,"Good" },
    {8,"Good" },
    {9,"Excellent" },
    {10,"Excellent" }
};

并且考虑到字典可能会因为程序的逻辑而改变,并且Automapper内部不需要有固定的字典,并且必须将这个字典发送到Automapper。现在我的问题是:如何通过发送此字典来根据学生在 Automapper 中的分数分配排名属性?

还有一个更普遍的问题。如果要计算的属性值要从数据库表中获取,那如何用ef Core将数据库注入到Automapper中呢?

我尝试根据 Automapper 指南发送对象,但没有成功

c# entity-framework-core automapper
1个回答
0
投票

就这样做:

 public  static class AutomapperExtensions
 { 
     private static Dictionary<byte,string> Ranks { get; } = new Dictionary<byte, string>() 
     {
        { 0, "rejected" },
        { 1, "very weak" },
        { 2, "very weak" },
        { 3, "weak" },
        { 4, "weak" },
        { 5, "medium" },
        { 6, "medium" },
        { 7, "Good" },
        { 8, "Good" },
        { 9, "Excellent" },
        { 10, "Excellent" }
     };

     public static void CreateMapping(IMapperConfigurationExpression cfg)
     {
         cfg.CreateMap<Student, StudentRankingDto>()
          .ForMember(x => x.Name, 
              opt => opt.MapFrom(x => x.FirstName + " " + x.LastName)
          .ReverseMap();

         cfg.CreateMap<Student, StudentRankingDto>()
          .ForMember(x => x.Rank, 
              opt => opt.MapFrom(x => Ranks[x.Score])
          .ReverseMap();
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.