gpt4 book ai didi

c# - 使用 linq to entity 进行嵌套查询

转载 作者:行者123 更新时间:2023-11-30 22:03:44 25 4
gpt4 key购买 nike

我有以下类(class):

public class A
{
public int Id {get;set;}
public string Name {get; set;}
public ICollection<B> Bs {get; set;}
}

public class B
{
public int Id {get;set;}
public string Name {get; set;}
public ICollection<C> Cs {get; set;}
}

public class C
{
public int Id {get;set;}
public string Name {get; set;}
}

还有这些ViewModels :

public class AViewModel
{
public int Id {get;set;}
public string Name {get; set;}
public ICollection<BViewModel> BViewModels {get; set;}
}
public class BViewModel
{
public string Name {get; set;}
public ICollection<CViewModel> CViewModels {get; set;}
}
public class CViewModel
{
public string Name {get; set;}
}

我想写一个linq to entity query( Fluent API ) 找到 A对象由其 Id结果是 AViewModel列表为 BViewModel s 和每个 BViewModel包括 CViewModels 的列表也,我写了以下查询,但它有一些错误:

 _uow.Repository<A>()
.All()
.Include("Bs")
.Include("Bs.Cs")
.Select(a => new AViewModel
{
Name = a.Name,
Id = a.Id,
(ICollection<BViewModel>)
a.Bs
.SelectMany(
t => a.Bs
.Select(r => new BViewModel()
{
Name = r.Name
Cs =
(ICollection<CViewModel>)
t.Cs.SelectMany(y => new CViewModel()
{
Name = y.Name
})
}
)
)
}
).FirstOrDefault(a => a.Id == 5);

我该怎么做?

最佳答案

尝试将 SelectMany 替换为 Select 并将类型转换 (ICollection) 替换为 ToList()

_uow.Repository<A>()
.All()
.Select(a => new AViewModel
{
Id = a.Id,
Name = a.Name,
Bs = a.Bs.Select(b => new BViewModel
{
Id = b.Id,
Name = b.Name,
Cs = b.Cs.Select(c => new CViewModel
{
Id = c.Id,
Name = c.Name
}).ToList()
}).ToList()
})
.FirstOrDefault(a => a.Id == Id);

关于c# - 使用 linq to entity 进行嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831104/

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