Linq查询填充ViewModel集合,包括子ViewModel集合

时间:2016-03-10 19:11:51

标签: c# linq

我正在尝试研究如何在Linq查询中获取对象及其子视图模型集合的集合。

假设您有这些模型:

public class Parent
{
    public int ParentId {get; set;}
    public string ParentName {get; set;}
    public virtual ICollection<FirstChild> FirstChildren { get; set; }
    public virtual ICollection<SecondChild> SecondChildren { get; set; }
}

public class FirstChild
{
    public int FirstChildId {get; set;}
    public int ParentId {get; set;}
    public string FirstChildName {get; set;}
}

public class SecondChild
{
    public int SecondChildId {get; set;}
    public int ParentId {get; set;}
    public string SecondChildName {get; set;}
}

然后你有一些viewModels:

public class ParentViewModel
{
    public int ParentId {get; set;}
    public string ParentName {get; set;}
    public virtual ICollection<FirstChild> FirstChildren { get; set; }
    public virtual ICollection<SecondChildViewModel> SecondChildren { get; set; }
}

public class SecondChildViewModel
{
    public int SecondChildId {get; set;}
    public int ParentId {get; set;}
    public string SecondChildName {get; set;}
}

是的,ParentViewModel将有一个模型集合和一个视图模型集合。

我想做一个linq查询,最终填充ParentViewModel列表并填充子集合。

var result = (from p in db.Parent.Include(p => p.FirstChildren).Include(p => p.SecondChildren)
            select new ParentViewModel {
                ParentId = p.ParentId,
                ParentName = p.ParentName,
                FirstChildren = p.FirstChildren,
                SecondChildren = p.SecondChildren as SecondChildViewModel
            });

处理这个问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

如果这一行

SecondChildren = p.SecondChildren as SecondChildViewModel

是问题所在,你应该简单地处理它,类似于Parent - &gt; ParentViewModel,即使用投影:

SecondChildren = p.SecondChildren.Select(c => new SecondChildViewModel {
    SecondChildId = c.SecondChildId,
    ParentId  = c.ParentId,
    SecondChildName = c.SecondChildName
}).ToList()

答案 1 :(得分:0)

尝试在Linq中使用dataloadoption。以下是使用代码的示例:

var dataContext = new dataContext();
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<FirstChildren>( p => p.FirstChildren);
dlo.LoadWith<SecondChildren>( p => p.SecondChildren);
dataContext.LoadOptions = dlo;

var result = (from p in dataContext.Parent
            select new ParentViewModel {
                ParentId = p.ParentId,
                ParentName = p.ParentName,
                FirstChildren = p.FirstChildren,
                SecondChildren = p.SecondChildren as SecondChildViewModel
            });

点击here,获取微软的一个好例子。