使用AutoMapper将EFcomplex实体映射到WCF DataContracts

时间:2013-07-30 15:09:09

标签: wcf entity-framework-4 automapper

我是AutoMapper的新手,我在我的应用程序中的Service Layer中的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中,订单嵌套在Customer内...如何使用AutoMapper反映此层次结构 提前致谢

1 个答案:

答案 0 :(得分: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