我不是Linq的新手但我无法解决这个问题。
假设我有以下型号。显然这是样本模型。
public class Parent
{
public int Id { get; set; }
public List<Child> Children { get; set; }
public DateTime CreateDate { get; set; }
}
public class Child
{
public int Id { get; set; }
public List<Toys> Toys { get; set; }
public DateTime CreateDate { get; set; }
}
public class Toys
{
public string Id { get; set; }
public string Name { get; set; }
public DateTime CreateDate { get; set; }
}
我想要的是将它们转换为ViewModels。这里我的ViewModel是如何定义的
public class ParentViewModel
{
public int Id { get; set; }
public List<ChildViewModel> Children { get; set; }
}
public class ChildViewModel
{
public int Id { get; set; }
public List<ToysViewModel> Toys { get; set; }
}
public class ToysViewModel
{
public string Id { get; set; }
public string Name { get; set; }
}
如何选择模型并将其转换为viewModels。 这是我已经尝试过的。
var q = from p in dbContext.Parents
where p.Id = 123
select new ParentViewModel
{
Id = p.Id,
Children = ???
};
如何获得儿童及其玩具清单?
提前致谢!
答案 0 :(得分:11)
如果关系在数据库中正确建模,那么
select new ParentViewModel
{
Id = p.Id,
Children = p.Children.Select(c => new ChildViewModel {
Id = c.Id,
Toys = c.Toys.Select(t => new ToyViewModel { ... }).ToList()
}).ToList()
};
答案 1 :(得分:3)
为了清楚起见,我宁愿把它分解成这样的函数:
public static ParentViewModel AsViewModel(Parent parent)
{
var childViewModels = parent.Children.Select(AsViewModel).ToList();
return new ParentViewModel { Id = parent.Id, Children = childViewModels };
}
public static ChildViewModel AsViewModel(Child child)
{
var toyViewModels = child.Toys.Select(AsViewModel).ToList();
return new ChildViewModel { Id = child.Id, Toys = toyViewModels };
}
public static ToyViewModel AsViewModel(Toy toy)
{
return new ToyViewModel { Id = toy.Id, Name = toy.Name };
}
然后就可以这样使用:
var q = dbContext.Parents.Where(p => p.Id == 123).Select(AsViewModel);
答案 2 :(得分:1)
考虑使用一些自动映射工具,例如Automampper。
定义某处映射:
Mapper.CreateMap<Parent, ParentViewModel>();
Mapper.CreateMap<Child, ChildViewModel>();
Mapper.CreateMap<Toys, ToysViewModel>();
和你的代码
Parent parent = GetParentById(123); // use LINQ to get parent
ParentViewModel pvm = Mapper.Map<ParentViewModel>(parent);
答案 3 :(得分:0)
我会使用 AutoMapper 将我的实体转换为模型。它很好地支持集合。
答案 4 :(得分:0)
你是说这个吗?
var q = from p in dbContext.Parents
where p.Id = 123
select new ParentViewModel
{
Id = p.Id,
Children = p.Children.Select(c => new ChildViewModel
{
Id = c.Id,
Toys = c.Toys.Select(t => new ToysViewModel
{
Id = t.Id
}).ToList()
}).ToList()
};
答案 5 :(得分:0)
保持自己的作品风格:
var q = from p in dbContext.Parents
where p.Id == 123
select new ParentViewModel
{
Id = p.Id,
Children = (from c in p.Children
select new ChildViewModel()
{
Id = c.Id,
Toys = (from t in c.Toys
select new ToyViewModel()
{
Id = t.Id,
Name = t.Name
}).ToList()
}).ToList()
};
我会拨打Toy
而不是Toys
和ToyViewModel
而不是ToysViewModel