简体   繁体   中英

C# automapper is not working with an entity class and model class

I'm trying to map Originator List to OriginatorModel list using this statement

 List<OriginatorModel> originatorModels=  mapper.DynamicMap<List<Originator>, List<OriginatorModel>>(originators);

I debugged, I have a quite few elements in the "originators" variable but after mapping statement, not getting any into "originatorModels" list variable.

Any help is appreciated !

Entity class: 
public class Originator : EntityBase
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Birth { get; set; }  // use string instead of DateTime


    public string Death { get; set; }  // use string instead of DateTime



    public string VIAFNumber { get; set; }

    public string ImageFilename { get; set; }

    public Originator()
    {
    }
    public Originator(string firstName, string lastName, string birth=null, string death=null)
    {
        FirstName = firstName;
        LastName = lastName;
        Birth = birth;
        Death = death;
    }


    }

Originator Model class:

 public class OriginatorModel
{

   public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FullName
    {
        get {
            string name = "";
            if ((!string.IsNullOrEmpty(FirstName)) && (!string.IsNullOrEmpty(LastName)))
            {
                name = LastName + ", " + FirstName;
            }
            else if (!string.IsNullOrEmpty(FirstName))
            {
                name = FirstName;
            }
            else
            {
                name = LastName;
            }

            return name;
          }
    }
    public string Birth { get; set; }
    public string Death { get; set; }


    public string VIAFNumber { get; set; }
    public string ImageFilename { get; set; }

}

I don't think you need to use the DynamicMapper. You know the source at compile type. Try using the normal Mapper.Map.

Try

     Mapper.CreateMap<Originator, OriginatorModel>();

     List<OriginatorModel> originatorModels = Mapper.Map<List<Originator>, List<OriginatorModel>>(originators);

You can create the map like this:

Mapper.CreateMap<Originator, OriginatorModel>();

Then do this:

var originatorModels = Mapper.Map<List<Originator>, List<OriginatorModel>>(originators);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM