使用AutoMapper从实体映射到DTO或DTO到实体时出错

本文关键字:实体 DTO 出错 映射 AutoMapper 使用 | 更新日期: 2023-09-27 18:13:38

我使用EntityFramework作为数据层和DTO在层之间传输数据。我在n层架构中开发Windows窗体,当我尝试在BLL中从实体映射到DTO时:

public IEnumerable<CategoryDTO> GetCategoriesPaged(int skip, int take, string name)
{
    var categories = unitOfWork.CategoryRepository.GetCategoriesPaged(skip, take, name);
    var categoriesDTO = Mapper.Map<IEnumerable<Category>, List<CategoryDTO>>(categories);
    return categoriesDTO;
}

我得到了这个错误:http://s810.photobucket.com/user/sky3913/media/AutoMapperError.png.html

错误提示缺少类型映射配置或不支持映射。我用这种方式在UI层注册了配置文件映射:

[STAThread]
static void Main()
{
    AutoMapperBusinessConfiguration.Configure();
    AutoMapperWindowsConfiguration.Configure();
    ...
    Application.Run(new frmMain());
}

和AutoMapper的配置在BLL:

public class AutoMapperBusinessConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<EntityToDTOProfile>();
            cfg.AddProfile<DTOToEntityProfile>();
        });
    }
}
public class EntityToDTOProfile : Profile
{
    public override string ProfileName
    {
        get { return "EntityToDTOMappings"; }
    }
    protected override void Configure()
    {
        Mapper.CreateMap<Category, CategoryDTO>();
    }
}
public class DTOToEntityProfile : Profile
{
    public override string ProfileName
    {
        get { return "DTOToEntityMappings"; }
    }
    protected override void Configure()
    {
        Mapper.CreateMap<CategoryDTO, Category>();
    }
}

当从DTO映射到实体时,我也有同样的错误。

category = Mapper.Map<Category>(categoryDTO);

如何解决这个问题?

使用AutoMapper从实体映射到DTO或DTO到实体时出错

这是因为您多次使用Mapper.Initialize。如果您查看源代码,它调用Mapper.Reset(),这意味着只有最后定义的映射才能工作。因此,只需删除Initialize调用并替换为Mapper.AddProfile< >

Configure()调用之后使用AutoMapper.AssertConfigurationIsValid()。如果任何操作失败,它将抛出一个带有描述性文本的异常。

使用AutoMapper和EntityFramework将dto映射到实体

这里我们有一个实体类Country和一个CountryDTO

 public class Country
 {
     public int CountryID { get; set; }
     public string ContryName { get; set; }
     public string CountryCode { get; set; }
 }

CountryDto

 public class CountryDTO
{
   public int CountryID { get; set; }
   public string ContryName { get; set; }
   public string CountryCode { get; set; }
}

创建CountryDTO对象

CountryDTO collection=new CountryDTO();
 collection.CountryID =1;
 collection.ContryName ="India";
 collection.CountryCode ="in";
Country model = Convertor.Convert<Country, CountryDTO>(collection);
dbcontext.Countries.Add(model);
dbcontext.SaveChanges();

对于一个新的国家来说,这将很好地工作,上面的代码将把CountryDTO映射到国家实体对象,并向dbcontext添加新的实体,并保存更改。

using System.Reflection;
public static TOut Convert<TOut, TIn>(TIn fromRecord) where TOut : new()
 {
  var toRecord = new TOut();
  PropertyInfo[] fromFields = null;
  PropertyInfo[] toFields = null;
  fromFields = typeof(TIn).GetProperties();
  toFields = typeof(TOut).GetProperties();
  foreach (var fromField in fromFields)
   {
    foreach (var toField in toFields)
      {
        if (fromField.Name == toField.Name)
          {
             toField.SetValue(toRecord, fromField.GetValue(fromRecord, null), null);
            break;
          }
      }
  }
return toRecord;
}
public static List<TOut> Convert<TOut, TIn>(List<TIn> fromRecordList) where TOut : new()
 {
  return fromRecordList.Count == 0 ? null : fromRecordList.Select(Convert<TOut, TIn>).ToList();
 }
http://bhupendrasinliaini.blogspot.in/2014/09/convert-enity-framwork-data-in-entity.html