use*_*807 0 linq entity-framework
我有一个实体模型,我一直在寻找一个linq查询,它返回每个祖父母的子女和父母的数量.
我需要输出3列:祖父母的姓名| 儿童数| 孙子的数量
protected void Page_Load(object sender, EventArgs e)
{
using (FamilyModel.TheConn myEntities = new FamilyModel.TheConn())
{
int TheUserID = 13; // will change later
var myOutput = from gparents in myEntities.GrandParents
where gparents.UserID == TheUserID
select gparent.Name, // here's what's missing: the counts
GridView1.DataSource = myOutput;
GridView1.DataBind();
}
}
Run Code Online (Sandbox Code Playgroud)
我一直在努力与SelectMany,Groupby,加入....我只是没有得到我需要这个看似简单的查询的结果.任何投入将不胜感激.
谢谢
var myOutput = from gparent in myEntities.GrandParents
where gparent.UserID == TheUserID
select new GrandParentViewModel
{
Name = gparent.Name,
ChildrenCount = gparent.Children.Count(),
GrandChildrenCount = gparent.Children.SelectMany(c => c.GrandChildren).Count()
};
Run Code Online (Sandbox Code Playgroud)
这假设您的Child实体具有导航属性GrandChildren(实际上这里的名称Children世界更有意义 - 儿童的孩子=孙子).
在这种情况下,我们投射到GrandParentViewModel:
public class GrandParentViewModel
{
public string Name { get; set; }
public int ChildrenCount { get; set; }
public int GrandChildrenCount { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1325 次 |
| 最近记录: |