使用Linq Select将实体映射到DTO的最简洁方法? [英] Cleanest Way To Map Entity To DTO With Linq Select?
问题描述
我一直在尝试提出一种干净且可重用的方法来将实体映射到其DTO.这是我想出的东西以及遇到问题的一个示例.
I've been trying to come up with a clean and reusable way to map entities to their DTOs. Here is an example of what I've come up with and where I'm stuck.
实体
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
// Other properties not included in DTO
}
public class Address
{
public int ID { get; set; }
public string City { get; set; }
// Other properties not included in DTO
}
DTO
public class PersonDTO
{
public int ID { get; set; }
public string Name { get; set; }
public AddressDTO Address { get; set; }
}
public class AddressDTO
{
public int ID { get; set; }
public string City { get; set; }
}
表达式
这就是我开始处理映射的方式.我想要一个不会在映射之前执行查询的解决方案.有人告诉我,如果您传递Func<in, out>
而不是Expression<Func<in, out>>
,它将在映射之前执行查询.
This is how I began to handle the mapping. I wanted a solution that wouldn't execute the query before mapping. I've been told that if you pass a Func<in, out>
instead of Expression<Func<in, out>>
that it will execute the query before mapping.
public static Expressions
{
public static Expression<Func<Person, PersonDTO>> = (person) => new PersonDTO()
{
ID = person.ID,
Name = person.Name,
Address = new AddressDTO()
{
ID = person.Address.ID,
City = person.Address.City
}
}
}
一个问题是我已经有了一个将Address
映射到AddressDTO
的表达式,所以我有重复的代码.如果person.Address
为null,这也会中断.这变得非常混乱,特别是如果我想在同一DTO中显示与人相关的其他实体时.它变成了嵌套映射的鸟巢.
One issue with this is that I already have an expression that maps an Address
to an AddressDTO
so I have duplicated code. This will also break if person.Address
is null. This gets messy very quick especially if I want to display other entities related to person in this same DTO. It becomes a birds nest of nested mappings.
我尝试了以下操作,但是Linq不知道如何处理.
I've tried the following but Linq doesn't know how to handle it.
public static Expressions
{
public static Expression<Func<Person, PersonDTO>> = (person) => new PersonDTO()
{
ID = person.ID,
Name = person.Name,
Address = Convert(person.Address)
}
public static AddressDTO Convert(Address source)
{
if (source == null) return null;
return new AddressDTO()
{
ID = source.ID,
City = source.City
}
}
}
我缺少任何优雅的解决方案吗?
Are there any elegant solutions that I'm missing?
推荐答案
只需使用 AutoMapper .
示例:
Mapper.CreateMap<Address, AddressDTO>();
Mapper.CreateMap<Person, PersonDTO>();
查询将在执行映射时执行,但是如果您不感兴趣的实体中有字段,请使用
Project().To<>
,该字段可用于NHibernate和EntityFramework.它将有效地对映射配置中指定的字段进行选择.
Your query will execute when the mapping is performed but if there are fields in the entity that you're not interested use
Project().To<>
which is available both for NHibernate and EntityFramework. It will effectively do a select on the fields specified in the mapping configurations.
这篇关于使用Linq Select将实体映射到DTO的最简洁方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!