当我尝试将集合从一个实体映射到另一个实体时出现自动映射问题

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

我正在使用自动映射器来映射具有相同类( .Map(Entity,Entity) )的两个对象,如下所示。

问题是当我尝试将集合从第一个实体映射到第二个实体时。我收到 NullReferenceException 。

当我从数据库检索实体时,关联的属性设置为 null(因为我允许它为 null)。

如何将一个集合映射到另一个集合,即使其中一个集合为空?

这是我尝试过的

  // here i retrieve the user from the DB
            var currentUser = await extendedRepository.GetByTokenAsync(changePasswordDto.TokenProp);

            if (currentUser == null)
            {
                throw new DbUpdateException("User not found");
            }
            
          
            Console.WriteLine("inainte Adrese conturi in current user : " + currentUser.AdreseConturi); // here i get null
            
            // this mapper works 
            // updatedUser.AdreseConturi is not null ( i'm using the constructor to map) , even tho currentUser is null
            var updatedUser = _mapper.Map<Conturi>(currentUser,
                opt => opt.Items["NewPassword"] = changePasswordDto.NewHashedPasswordProp);
  
            ICollection<Adrese>? adreses = currentUser.AdreseConturi; // this is null , set only for testing purpose to see the value
            // and when i try to map here , i get the NullReferenceException from the AdreseConturi 
            _mapper.Map(updatedUser, currentUser);

这是我的地图制作者个人资料:

// the entity to entity simpler mapper
CreateMap<Conturi, Conturi>()
            .ForAllMembers(options => options.Ignore());

// the entity to entity mapper where i needed to change passwords 
CreateMap<Conturi, Conturi>()
            .ConstructUsing((src, context) =>
            {
                var newPassword = context.Items.TryGetValue("NewPassword", out var newPasswordObj) ? newPasswordObj as string : src.Parola;
                
                return new Conturi(
                    src.Nume,
                    src.Prenume,
                    src.Gen,
                    src.NrTelefon,
                    src.Username,
                    src.Email,
                    newPassword,
                    src.DataCreare,
                    src.CodActivare,
                    src.Verificat,
                    src.Rol,
                    src.OraLinkConfirmare,
                    src.AdreseConturi
                );
                
            });

---

这是我的实体:

public  class Conturi : ICloneable
{
    /* other atributes, irrelevant for the problem */ 

    public  ICollection<Adrese>? AdreseConturi { get;}

    public Conturi()
    {
        
    }

    public Conturi(string? nume, string? prenume, bool? gen, string? nrTelefon, string username, 
                   string email, string parola, DateTime? dataCreare, 
                   string codActivare, bool verificat, string rol ,DateTime oraLinkConfirmare,ICollection<Adrese>? adreseConturi)
    {
        Nume = nume;
        Prenume = prenume;
        Gen = gen;
        NrTelefon = nrTelefon;
        Username = username;
        Email = email;
        Parola = parola;
        DataCreare = dataCreare;
        CodActivare = codActivare;
        Verificat = verificat;
        Rol = rol;
        OraLinkConfirmare = oraLinkConfirmare;
        AdreseConturi = adreseConturi == null ? new HashSet<Adrese>() : new HashSet<Adrese>(adreseConturi);
       
    }

这就是错误:

AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Conturi -> Conturi
E_Commerce_BackEnd.Models.UserRelatedModels.Conturi -> E_Commerce_BackEnd.Models.UserRelatedModels.Conturi

Type Map configuration:
Conturi -> Conturi
E_Commerce_BackEnd.Models.UserRelatedModels.Conturi -> E_Commerce_BackEnd.Models.UserRelatedModels.Conturi

Destination Member:
AdreseConturi

 ---> System.NullReferenceException: Object reference not set to an instance of an object.
/* rest of the error */

---

我怎样才能克服这个错误或者我怎样才能解决它,如果你能好心地解释我问题出在哪里并让我理解它。非常感谢!

c# asp.net automapper
1个回答
0
投票

你可以做类似的事情

ICollection<Adrese>? adreses = ((currentUser.AdreseConturi != null) ? currentUser.AdreseConturi : somefallback);

但是,当然,您需要定义

somefallback
。它可能是一个空集合,甚至是
updatedUser.AdreseConturi
,具体取决于最适合您的需求。

© www.soinside.com 2019 - 2024. All rights reserved.