【问题标题】:How to use Automapper 5?如何使用 Automapper 5?
【发布时间】:2017-02-21 10:22:56
【问题描述】:

我是 Automapper 的新手。通过下面的链接,我正在努力理解它。

我正在使用它的 Automapper v 5.2.0

这是我的东西。 https://codepaste.net/xph2oa

class Program
{
    static void Main(string[] args)
    {
        //PLEASE IGNORE NAMING CONVENTIONS FOR NOW.Sorry!!
        //on Startup 
        AppMapper mapperObj = new AppMapper();
        mapperObj.Mapping();

        DAL obj = new DAL();
        var customer = obj.AddCustomers();


    }
}

class Customer
{
    public int CustomerId { get; set; }

    public string CustName { get; set; }
}


class CustomerTO
{
    public int CustId { get; set; }

    public object CustData { get; set; }
}


class AppMapper
{
    public void Mapping()
    {
        var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<Customer, CustomerTO>();
                    });

        IMapper mapper = config.CreateMapper();

    }
}

class DAL
{
    public IEnumerable<CustomerTO> AddCustomers()
    {
        List<Customer> customers = new List<Customer>();
        customers.Add(new Customer() { CustName = "Ram", CustomerId = 1 });
        customers.Add(new Customer() { CustName = "Shyam", CustomerId = 2 });
        customers.Add(new Customer() { CustName = "Mohan", CustomerId = 3 });
        customers.Add(new Customer() { CustName = "Steve", CustomerId = 4 });
        customers.Add(new Customer() { CustName = "John", CustomerId = 5 });

        return customers;   //throws error

    }
}

错误 - 无法将类型 System.Collections.Generic.List' 隐式转换为 'System.Collections.Generic.IEnumerable'。存在显式转换(您是否缺少演员表?)

如何将List&lt;Customer&gt; 映射到List&lt;CustomerTO&gt;

请注意,在Customer 中,我的属性为string,名称为Custname,而CustomerTO 我的属性为CustData,类型为object。 那么如何映射这个不同的名称属性呢?

谢谢。

【问题讨论】:

  • 检查this 我认为它会帮助你。但是不知道能不能把mapstring改成object
  • 你看过维基吗?它有最新的文档,而不是我的博客,它可能已经过时(例如静态 API 仍然存在,并且将会存在)。
  • @JimmyBogard,感谢您的博客。你的博客+其他一些链接足以让我开始。我还没有查看 wiki。

标签: c# asp.net automapper automapper-5


【解决方案1】:

对要映射的类型中的属性使用相同的名称是我们 AutoMapper 最简单的方法。这样你现在的配置就可以工作了。

但是,如果您不这样做,则需要指定属性的映射方式,如下所示

cfg.CreateMap<Customer, CustomerTO>()
.ForMember(dto => dto.CustData, opt => opt.MapFrom(entity => entity.CustName))
.ForMember(dto => dto.CustId, opt => opt.MapFrom(entity, entity.CustomerId));

我假设您想将上面的 CustName 直接映射到 CustData,这样可以正常工作。

【讨论】:

  • 假设我在 Customer & CustomerTO 中有 10 多个属性。 9 个属性名称相同,但 1 个属性名称和类型不同。在这种情况下,我需要写 .ForMember 10 次??
  • 不,您只需要指定名称不同的成员即可。
  • 您能否检查更新后的帖子,我在 DAL 方法中遇到构建错误
  • AddCustomers() 方法中的任何时候,您实际上都没有从Customer 映射到CustomerTO。您需要在 AppMapper 类的实例上调用 .Map&lt;IEnumerable&lt;CustomerTO&gt;&gt;(customers);
  • 在 Main() 中我做了,所以我需要再次关联这个映射胶水??
猜你喜欢
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
相关资源
最近更新 更多