gpt4 book ai didi

c# - 使用 Linq Select 将实体映射到 DTO 的最简洁方法?

转载 作者:可可西里 更新时间:2023-11-01 07:45:37 25 4
gpt4 key购买 nike

我一直在努力想出一种干净且可重用的方法来将实体映射到它们的 DTO。这是我想出的例子以及我被困的地方。

实体

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>>它将在映射之前执行查询。

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,这也会中断一片空白。这很快就会变得困惑,特别是如果我想在同一个 DTO 中显示与人相关的其他实体。它变成了嵌套映射的鸟巢。

我尝试了以下方法,但 Linq 不知道如何处理。

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
}
}
}

是否有任何我遗漏的优雅解决方案?

最佳答案

如果您想手动创建映射,则可以按以下方式在集合上使用 Select:

部分测试数据:

    var persons = new List<Person>
{
new Person() {ID = 1, Name = "name1", Address = new Address() {ID = 1, City = "city1"}},
new Person() {ID = 2, Name = "name2", Address = new Address() {ID = 2, City = "city2"}},
new Person() {ID = 3, Name = "name3", Address = new Address() {ID = 1, City = "city1"}}
};

映射方法:

    public static PersonDTO ToPersonDTOMap(Person person)
{
return new PersonDTO()
{
ID = person.ID,
Name = person.Name,
Address = ToAddressDTOMap(person.Address)
};
}

public static AddressDTO ToAddressDTOMap(Address address)
{
return new AddressDTO()
{
ID = address.ID,
City = address.City
};
}

实际使用情况:

var personsDTO = persons.Select(x => ToPersonDTOMap(x)).ToList();

请记住,如果这是一个真正的查询,只要它是 IQueryable 就不会执行,它会在您实现它后执行(例如使用 ToList())。

但是,我会考虑使用一些可以自动为您完成(映射)的框架(如果您的映射与提供的示例一样简单(。

关于c# - 使用 Linq Select 将实体映射到 DTO 的最简洁方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29613779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com