获取查询的值以成为另一个查询的一部分

时间:2014-02-15 19:23:25

标签: c# linq-to-entities

我正在尝试使用signerID的值作为另一个查询中where子句的一部分,但是得到带有错误的红色下划线:“delegate不接受1个参数”。基本上我想在查询allDepartments的where子句中使用signerID查询(value = 15)的值。这是代码:

 using (dbPSREntities10 myEntities = new dbPSREntities10())
        {
            int theStatus = Convert.ToInt32(ddlChangeStatus.SelectedValue);
            string userName = HttpContext.Current.User.Identity.Name;

            var signerID = (from refAuthSigner in myEntities.refAuthSigners.Where(x => x.NetworkUsername == userName)
                            select new
                                  {
                                      refAuthSignerID = refAuthSigner.refAuthSignerID
                                  }); <---- here I should have the value 15

            var allDepartments = (from tbProject in myEntities.tbProjects.Where(x => x.refAuthSignerID == signerID)<-- and I want to use the value of signerID (15) here

这样离开了吗?我可以在where clasue中用硬编码15代替signerID,一切正常。提前谢谢!

1 个答案:

答案 0 :(得分:1)

我建议你加入关于歌手身份的表格:

var allDepartments = 
    from p in myEntities.tbProjects
    join s in myEntities.refAuthSigners
        on p.refAuthSignerID equals s.refAuthSignerID
    where s.NetworkUsername == userName
    select p;

此查询将仅选择那些歌手ID等于歌手身份且具有提供名称的项目。


当然,你可以在两个查询中完成所有 - 通过第一个查询获取id,并在第二个查询中使用id:

int singerId = myEntities.refAuthSigners
                         .Where(s => s.NetworkUsername == userName)
                         .Select(s => s.refAuthSignerID)
                         .FirstOrDefault(); // execute first query

if (singerId == 0)
    return; // singer not found

// build second query
var allDepartments = myEntities.tbProjects
                               .Where(p => p.refAuthSignerID == signerID);