【发布时间】:2013-12-05 20:22:04
【问题描述】:
我正在使用 Entity Framework Code First 并尝试从我的实体类映射到我的 DTO 类。但是我很难弄清楚如何编写选择器。
在这个小例子中,我创建了一个 Person 类和一个 Address 类。
在 DTO 类中,我创建了一个选择器,它从我的实体映射到我的 DTO,但是不能在 PersonDto.Selector 中使用 AddressDto.Selector 吗?
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
}
现在我正在尝试将其映射到 DTO 类。
public class PersonDto
{
public static Expression<Func<Person, PersonDto>> Selector =
entity => new PersonDto
{
Id = entity.Id,
Name = entity.Name,
Address = ??? AddressDTO.Selector
};
public int Id { get; set; }
public string Name { get; set; }
public AddressDto Address { get; set; }
}
public class AddressDto
{
public static Expression<Func<Address, AddressDto>> Selector =
entity => new AddressDto
{
Id = entity.Id,
Street = entity.Street
};
public int Id { get; set; }
public string Street { get; set; }
}
我知道我可以在 PersonDto.Selector 中写这个
Address = new AddressDto
{
Id = entity.Address.Id,
Street = entity.Address.Street
};
但我正在寻找一种方法来重用 AddressDto 类中的 Selector。保持代码整洁并在类之间分离职责。
【问题讨论】:
标签: c# .net entity-framework dto