C# 如何根据Id向LINQ查询添加条件

C# 如何根据Id向LINQ查询添加条件,c#,asp.net-mvc,linq,C#,Asp.net Mvc,Linq,这是我的操作方法,它获取所有用户的Id public JsonResult GetUsers() { var ret = (from user in db.Users.ToList() select new { UserName = user.UserName, // i am stuck here, i want to get all those ids whom current logged

这是我的操作方法,它获取所有用户的Id

public JsonResult GetUsers()
 {
  var ret = (from user in db.Users.ToList()
              select new 
               {
                UserName = user.UserName,
 // i am stuck here, i want to get all those ids whom current logged  user is following
                Idfollowing = user.FollowTables.Contains()
                Idnotfollowing = 
                 });
        return Json(ret, JsonRequestBehavior.AllowGet);
  }
下表的结构如下:

ID  UserId  FollowId
1    4        11
2    4        12
2    4        13
在这里,当前loggedin用户的id是4,他正在跟踪11、12、13,所以我只想将11、12和13返回到Idfollowing,剩余的id在Idnotfollowing中。如何完成它

好吧,我想用列表或数组,我不会得到想要的结果。所以,我想在这里补充一些东西。 好的,每个用户名都会传递一个id到查看页面。我把它们分成两部分。现在,如何给这些ID赋值

将User.Id与用户的followId列中的当前日志相匹配。如果找到匹配项,即如果Id匹配或找到,则将该User.Id分配给Idfollowing,将null分配给Idnotfollowing,反之亦然。 我必须根据返回的这些ID生成follow unfollow按钮

 public JsonResult GetUsers()
    {
        int currentUserId = this.User.Identity.GetUserId<int>();
        var ret = (from user in db.Users.ToList()
                   let Id = user.FollowTables.Where(x => x.UserId == currentUserId).Select(f => f.FollowId).ToList()
                   let Idnot = (from user2 in db.Users
                                where !Id.Contains(user2.Id)
                                select user2.Id).ToList()
                   select new
                   {
                       UserName = user.UserName,
                       Id = Id,
                       //Id = user.FollowTables.Where(x => x.UserId == currentUserId)
                       //       .Select(x => x.FollowId).Single(),
                       Idnot = Idnot, 
publicjsonresult GetUsers()
{
int currentUserId=this.User.Identity.GetUserId();
var ret=(来自db.Users.ToList()中的用户)
让Id=user.FollowTables.Where(x=>x.UserId==currentUserId)。选择(f=>f.FollowId.ToList())
让Idnot=(来自db.Users中的user2
其中!Id.Contains(user2.Id)
选择user2.Id).ToList()
选择新的
{
UserName=user.UserName,
Id=Id,
//Id=user.FollowTables.Where(x=>x.UserId==currentUserId)
//.Select(x=>x.FollowId).Single(),
Idnot=Idnot,

这很难看,但会起作用,必须有另一种更好的方法。

您可以简单地使用
Where
方法筛选表,并使用
Select
投影
FollowiId
:-

var ret = (from user in db.Users.ToList()
           select new 
             {
                UserName = user.UserName,
                Idfollowing = user.FollowTables.Where(x => x.UserId == user.Id)
                                  .Select(x => x.FollowId).ToArray(),
                Idnotfollowing = user.FollowTables.Where(x => x.UserId != user.Id)
                                  .Select(x => x.FollowId).ToArray()
            });

假设,
Idfollowing
Idnotfollowing
是数组if整数(if
followind
是整数)否则,如果它是一个列表,您可以将其替换为
ToList

看起来您有一个从
User
FollowTable
的标准一对多关系。此数据模型强制执行
User。FollowTables
仅包含追随者。您将无法从<代码>下表属性

类似的方法可能会奏效:

var query = (
    from user in db.Users // note: removed ToList() here 
                          // to avoid premature query materialization
    where //TODO ADD WHERE CLAUSE HERE ?
    let followIds = user.FollowTables.Select(f => f.FollowId)
    let notFollowIds = (from user2 in db.Users
                        where !followIds.Contains(user2.Id)
                        select user2.Id)
    select new 
    {
        UserName = user.UserName,
        Idfollowing = followIds.ToArray(),
        Idnotfollowing = notFollowIds.ToArray()
    })
     // TODO add paging? .Skip(offset).Take(pageSize)
     .ToList();
请验证此查询生成的SQL,并确保其执行正常


另外,请注意,我从
db.Users.ToList()中删除了
.ToList()
为了避免过早的查询具体化。从一个表中提取所有数据而不受约束通常是一个坏主意,您通常需要一个

Idnotfollowing=!Idfollowing
,对吗?是的,它应该返回剩余的所有id@kienct89its整数,并且我必须在另一个列表中返回tolist吗top@duke-Duke没有抓到你。
IDfollow
将具有多个Id的权限?因此你需要将其存储在列表或数组中。工作不正常,返回的数据为[{“用户名”:“sachin”,“IDfollow”:[],“IDNotFollow”:[],“IDNotFollow”:[],“IDNotFollow”:[8],{“用户名”:“dhoni”,“IDfollow”:[],“IDNotFollow”:[],“IDNotFollow”:[]。]这里当前登录的用户是sachin,他的用户ID是7,他只关注第8个用户ID,我在.ToList和ToArray@Rahul上得到了相同的结果Singh@duke-调试时检查
用户是否正常。下表
中是否有id为
7
的数据?yupp它有数据我已在此处查看数据将console.log放在此处,如下所示--$.getJSON(“/Home/GetUsers”,null,函数(数据){alert(JSON.stringify(data));在controller中,我看不到返回的内容@Rahul Singhthnks将尝试它。很好,我已经尝试过了。它正在返回这个JSON[{“UserName”:“sachin”,“idfollow”:[],“idnotfollow”:[8,9,7],{“UserName”:“dravid”,“idfollow”:[8],“Idnotfollowing”:[7,9]},{“UserName”:“dhoni”,“Idfollowing”:[],“Idnotfollowing”:[8,9,7]}]这里,当前登录的用户是sachin,他的用户ID是7,他只关注第8个用户ID。实际上,我必须根据这些ID在查看页面上生成follow unfollow按钮。如果需要,我是否也要显示u查看页面@jeroenhsee my edit:从db.Users.ToList()中删除ToList()此外,考虑添加WHERE子句和/或分页,以避免从内存中的整个表中获取所有数据,关注当前的问题。问题是如何从数据库中检索数据,而不是如何在HTML中可视化该数据。如果与后者有问题,请另行提问。删除.ToList但随后PostedByAvatar=\u GenerateAvatarUrlForUser(apost.PostedBy),此行出现问题,我在此代码中未显示此问题LINQ to Entities无法识别方法'System.String'\u GenerateAvatarUrlForUser(System.Nullable`1[System.Int32])'方法,此方法无法转换为存储表达式。首先设置EF查询,然后将其具体化(使用ToList()),然后执行不转换为SQL的转换。您需要了解LINQ工作原理的一些基础知识。
var query = (
    from user in db.Users // note: removed ToList() here 
                          // to avoid premature query materialization
    where //TODO ADD WHERE CLAUSE HERE ?
    let followIds = user.FollowTables.Select(f => f.FollowId)
    let notFollowIds = (from user2 in db.Users
                        where !followIds.Contains(user2.Id)
                        select user2.Id)
    select new 
    {
        UserName = user.UserName,
        Idfollowing = followIds.ToArray(),
        Idnotfollowing = notFollowIds.ToArray()
    })
     // TODO add paging? .Skip(offset).Take(pageSize)
     .ToList();