来自更多表的linq查询

时间:2009-11-19 12:30:50

标签: c# linq select join

public ActionResult myItems() {

        var dataContext = new RecordsDataContext();
        MembershipUser myObject = Membership.GetUser();         
        string CurrentUserName = myObject.UserName.ToString();    

       var user = from i in dataContext.myUsers
                   where i.userName ==CurrentUserName
                   select i.id;

        var items=from j in dataContext.OtherUsers
                   where j.id_user==user   /*error:operator '==' cannot be aplied to operands of type 'int' and 'System.Linq.Iquerable<int>'*/
                   select j;



           return View(items);

    }

请帮我解决此错误

1 个答案:

答案 0 :(得分:0)

实际上,第一个查询中的用户不是单个int结果。您需要检查user.Count()是否不为0,并且您可以使用user.First()来检索第一行结果。

但我建议使用join(类似的东西):

public ActionResult myItems() {
    var dataContext = new RecordsDataContext();
    var query = from i in dataContext.myItems
                join ou in dataContext.OtherUsers
                on i.id_user equals ou.id_user //check real reference, since I don't know
                join mu in dataContext.myUsers
                on ou.id_user equals mu.id_user
                where mu.username == Membership.GetUser().UserName.ToString()
                select i;
    return View(query);
}