c# – 如何使用Linq选择具有一对多关系的所有内容
发布时间:2020-12-15 22:44:02 所属栏目:百科 来源:网络整理
导读:我有两张桌子: CREATE TABLE Thing ( Id int,Name nvarchar(max));CREATE TABLE SubThing ( Id int,Name nvarchar(max),ThingId int (foreign key) ); 我想选择所有具有SubThings列表的东西并将它们设置为ThingViewModel. Thing ViewModel很简单: public c
我有两张桌子:
CREATE TABLE Thing ( Id int,Name nvarchar(max) ); CREATE TABLE SubThing ( Id int,Name nvarchar(max),ThingId int (foreign key) ); 我想选择所有具有SubThings列表的东西并将它们设置为ThingViewModel. Thing ViewModel很简单: public class ThingViewModel { public int Id { get; set; } public string Name { get; set; } public List<SubThingViewModel> SubThings { get; set; } } SubThingViewModel是: public class SubThingViewModel { public int Id { get; set; } public string Name { get; set; } } 我已经选择了像这样的Thing记录: List<ThingViewModel> things = null; things = _context.Things.OrderBy(b => b.Name) .Select(b => new ThingViewModel { Id = b.Id,Name = b.Name }).ToList(); 如何将SubThings添加到查询和ViewModel? 解决方法
您可以使用SubThings
navigation property进行另一次投影:
things = _context.Things.OrderBy(b => b.Name) .Select(b => new ThingViewModel { Id = b.Id,Name = b.Name,SubThings =b.SunThings.Select(st=>new SubThingViewModel{Id =st.Id,...}).ToList() }).ToList(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |