假设我们有两个类:
A:
[Key]
public long Id {get;set;}
public string SomeValueFromAddressTable {get;set;}
public string SomeValueFromPersonTable {get;set;}
public string SomeValueFromOrderTable {get;set;}
public long BId {get;set;}
B:
[Key]
public long Id {get;set;}
public IQUerable<A> AList {get;set;}
表示从数据库表中获取一些数据的Dbo对象(它们不是精确的数据库实体表示) - 是否可以在Linq语句中填充AList变量?我尝试使用一些技巧,但似乎无法达到我想要的效果。
编辑:
好的,请允许我解释一下:
我有标准数据库 - 例如 - 用户表有地址和其他一些表的外键。我想以DTO(User.Id,User.Name,User.Address.City,User.Address.Street)的形式从这些表中获取一些数据,用户可以有多个地址(一对多关系)。我创建了两个DTO类:
UserDto:
[Key]
public long Id {get;set;}
public string Name {get;set;}
public IQuerable<AddressDTO> AddressList {get;set;}
AddressDTO:
[Key]
public long Id {get;set;}
public string City {get;set;}
public string Street {get;set;}
我尝试过这样的事情:
var userQuery =
from user in Context.Users
join address in Context.Address on user.Id equals address .UserId
where address.IsActive=true
select new UserDto
{
Id = user.Id,
Name = user.Name,
AddressList = (from c in address select new AddressDTO
{
Id = c.Id,
City = c.City,
Street = c.Street
}).AsQuerable()
}
但它不会编译 - 如果我更改行:
from c in address select new AddressDTO
以下
from c in user.Addresses select new AddressDTO
然后它会编译,但我认为它不会考虑“where”条件。所以问题是 - 是否有可能以某种方式填补我的这种情况?我希望现在更清楚了。
答案 0 :(得分:1)
您可以在这种情况下使用组:
var userQuery = (
from user in Context.Users
join address in Context.Address on user.Id equals address.UserId
where address.IsActive = true
select new { userId = user.Id, userName = user.Name, addressId = address.Id, address.City, address.Street } into tmp
group tmp by new { tmp.userId, tmp.userName, adresses = grouped.ToList() } into grouped
select new UserDto
{
Id = grouped.Key.userId,
Name = grouped.Key.userName,
AddressList = grouped.Select(c => new AddressDTO
{
Id = c.addressId,
City = c.City,
Street = c.Street
})
}).ToList();