简体   繁体   English

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

[英]Error when mapping from Entity to DTO or DTO to Entity using AutoMapper

I'm using EntityFramework as a DataLayer and DTO to transfer data between layer. 我正在使用EntityFramework作为DataLayer和DTO在层之间传输数据。 I develop Windows Forms in N-Tier architecture and when I try to mapping from Entity to DTO in BLL: 我在N-Tier架构中开发Windows窗体,当我尝试在BLL中从Entity映射到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;
}

I've got this error: http://s810.photobucket.com/user/sky3913/media/AutoMapperError.png.html 我有这个错误: http//s810.photobucket.com/user/sky3913/media/AutoMapperError.png.html

The error said that I missing type map configuration or unsupported mapping. 该错误表示我缺少类型映射配置或不支持的映射。 I have registered mapping using profile in this way at UI Layer: 我已经在UI层以这种方式使用配置文件注册了映射:

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

and AutoMapper configuration is in BLL: 和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>();
    }
}

I've got the same error too when mapping from DTO to Entity. 从DTO映射到Entity时,我也遇到了同样的错误。

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

How to solve this? 怎么解决这个?

Its because you are using Mapper.Initialize multiple times. 这是因为你多次使用Mapper.Initialize If you look at the source code it calls Mapper.Reset() which means only the last mapping defined will work. 如果查看源代码,则调用Mapper.Reset() ,这意味着只有最后定义的映射才有效。 so instead simply remove the Initialize calls and replace with Mapper.AddProfile< > 所以只需删除Initialize调用并替换为Mapper.AddProfile< >

Use AutoMapper.AssertConfigurationIsValid() after the Configure() calls. Configure()调用之后使用AutoMapper.AssertConfigurationIsValid() If anything fails it will throw an exception with a descriptive text. 如果有任何失败,它将抛出带有描述性文本的异常。 It should give you more info to debug further. 它应该为您提供更多信息以进一步调试。

Mapping DTOs to Entities using AutoMapper and EntityFramework 使用AutoMapper和EntityFramework将DTO映射到实体

here we have an Entity class Country and an CountryDTO 这里我们有一个Entity类Country和一个CountryDTO

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

CountryDto CountryDto

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

Create Object of CountryDTO 创建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();

this will work fine for a new Country, the above code will map CountryDTO to Country Entity Object and add new entities to the dbcontext and save the changes. 这将适用于新的国家/地区,上述代码将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://bhupendrasinghsaini.blogspot.in/2014/09/convert-enity-framwork-data-in-entity.html http://bhupendrasinghsaini.blogspot.in/2014/09/convert-enity-framwork-data-in-entity.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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