Entity Framework + AutoMapper ( Entity to DTO and DTO to Entity )

后端 未结 8 1392
逝去的感伤
逝去的感伤 2021-01-30 07:38

I\'ve got some problems using EF with AutoMapper. =/

for example :

I\'ve got 2 related entities ( Customers and Orders ) and they\'re DTO classes :

         


        
8条回答
  •  不知归路
    2021-01-30 08:09

    Now, with new version of AutoMapper, the recommended way is using Queryable-Extensions:

    When using an ORM such as NHibernate or Entity Framework with AutoMapper's standard Mapper.Map functions, you may notice that the ORM will query all the fields of all the objects within a graph when AutoMapper is attempting to map the results to a destination type.

    If your ORM exposes IQueryables, you can use AutoMapper's QueryableExtensions helper methods to address this key pain.

    The .ProjectTo() will tell AutoMapper's mapping engine to emit a select clause to the IQueryable that will inform entity framework that it only needs to query the Name column of the Item table, same as if you manually projected your IQueryable to an OrderLineDTO with a Select clause.

    Create a mapping:

    Mapper.CreateMap();
    

    And project query to dto:

    var customerDto = 
       session.Query().Where(customer => customer.Id == id)
       .Project().To()
       .Single();
    

提交回复
热议问题