-1

我是 AutoMapper 的新手,我在应用程序的服务层中的 CustomerService 中有以下手动映射,我试图在其中找到等效的 AutoMapper 映射代码,但由于嵌套和复杂的对象和集合而无法找到,所以请帮忙我来解决这个问题

这里来自 CustomerService 的代码:Service.Customer 是 DataContract 和 Data.Customer 是实体

public Service.Customer GetCustomer(string customerID)
    {
        Data.Customer customer
            = _northwindEntities
                .Customers.Single(
                    c => c.CustomerID == customerID);
        return new Service.Customer
                   {
                       CustomerID = customer.CustomerID,
                       CompanyName = customer.CompanyName,
                       ContactName = customer.ContactName,
                       Address = customer.Address,
                       City = customer.City,
                       Country = customer.Country,
                       Region = customer.Region,
                       PostalCode = customer.PostalCode,
                       Phone = customer.Phone,
                       Orders 
                        = GetOrders(customer.Orders)
                   };
    }

Service.Order 是 DataContract 和 Data.Order 是实体...

private static IEnumerable<Service.Order> GetOrders(
        IEnumerable<Data.Order> order)
    {
        return order.Select(o => new Service.Order
            {
                OrderID = o.OrderID,
                OrderDate = o.OrderDate,
                OrderDetails = GetOrderDetails(o),
                Freight = o.Freight,
                ShippedDate = o.ShippedDate
            }).ToList();
    }

Service.OrderDetail 是 DataContract 和 Data.Order 是实体...

private static IEnumerable<Service.OrderDetail> GetOrderDetails(
        Data.Order order)
    {

        return order.Order_Details.Select(
            o => new Service.OrderDetail
            {
                Product 
                    = new Service.Product
                    {
                        ProductID 
                            = o.Product.ProductID,
                        ProductName 
                            = o.Product.ProductName
                    },
                Quantity = o.Quantity,
                UnitPrice = o.UnitPrice
            }).ToList();
    }

所以 OrderDetails 嵌套在 Oreders 和 Orders 嵌套在 Customer ...如何使用 AutoMapper 反映这种层次结构提前谢谢

4

1 回答 1

0

您需要为 Parent 类和所有嵌套类定义映射,然后您可以根据您的要求自定义它们

 Mapper.CreateMap<Data.Customer, Service.Customer>();
 Mapper.CreateMap<Data.Order, Service.Order>();
 Mapper.CreateMap<Data.OrderDetails, Service.OrderDetails>();
 Mapper.CreateMap<Data.Product, Service.Product>();   

看看这个

http://automapper.codeplex.com/wikipage?title=Nested%20Mappings

于 2013-07-31T03:34:27.027 回答