【发布时间】:2014-01-21 21:49:13
【问题描述】:
假设我在 EF 模型中有两个项目可以投影到以下 DTO:
public class AddressDto
{
public int Id { get; set; }
public string Address { get; set; }
public static Expression<Func<Address, AddressDto>> Address2AddressDto()
{
return x => new AddressDto() {
Id = x.Id,
FullName = x.AddressLine
};
}
}
public class ClientDto
{
public int Id { get; set; }
public int FullName { get; set; }
public AddressDto Address { get; set; }
}
如何为ClientDto 创建一个投影,重复使用来自AddressDto 的投影来转换嵌套在Address 中的Client?基本上我想要这样的东西:
public static Expression<Func<Client, ClientDto>> Client2ClientDto()
{
return x => new ClientDto() {
Id = x.Id,
FullName = x.FullName,
Address
= <Apply projection AddressDto.Address2AddressDto to object x.Address>
};
}
我知道我可以做到:
public static Expression<Func<Client, ClientDto>> Client2ClientDto()
{
return x => new ClientDto() {
Id = x.Id,
FullName = x.FullName,
Address = new AddressDto() {
Id = x.Id,
FullName = x.AddressLine
}
};
}
但我想在一个地方管理 AddressDto 投影,而不是在每个使用此投影的地方(实际对象要复杂得多,从长远来看,代码重复会导致问题)。
在我的调用者代码中,我想做类似的事情
dbRepo.Clients.Select(Client2ClientDto())
我当前的所有尝试都以异常结束:
LINQ to Entities 不支持 LINQ 表达式节点类型“Invoke”。
【问题讨论】:
标签: c# .net linq projection