【问题标题】:Using Entity Framework and check if userid exists in another table使用实体框架并检查用户 ID 是否存在于另一个表中
【发布时间】:2014-04-08 22:04:30
【问题描述】:

使用 MVC3、EntityFramework 4、C#、VS 2010,我得到了以下内容:

foreach (var person in _db.People.OrderByDescending(p => p.LastUpdated))
        {
            data.Add(new List<string>
            {
                person.UserId,
                person.FullName,
                person.Title
            }    
        }

return Json(data, JsonRequestBehavior.AllowGet);

我想添加一个列/字段来检查另一个实体对象以查看该人是否存在于另一个表中,然后在他们存在/不存在时显示 Y/N。

我该如何处理?

【问题讨论】:

  • 什么数据?你的两张桌子在哪里?如果您使用 linq,则不需要块

标签: c# json visual-studio-2010 asp.net-mvc-3 entity-framework


【解决方案1】:

如果我的猜测是正确的,您希望字符串列表中的另一列告诉您 "Y" 是否有人在该表上,如果不存在则 "N"。尝试这样做:

foreach (var person in _db.People.OrderByDescending(p => p.LastUpdated))
        {
            data.Add(new List<string>
            {
                person.UserId,
                person.FullName,
                person.Title,
                (_db.AnotherTable.Where(p => p.personID == person.personID).FirstOrDefault() == null? "Y": "N")
            }    
        }

【讨论】:

  • 就是这样!为了我们的目的,我不得不交换“Y”和“N”,但它就像一个魅力。它确实减慢了应用程序的速度,但它正在工作。非常感谢!
  • 很高兴帮助@sharcfinz。如果您喜欢这个答案,请不要忘记点赞。谢谢。
【解决方案2】:

在 People 表中添加外键是正确的。 然后您可以直接从对象访问关系。 像这样的

foreach (var person in _db.People.OrderByDescending(p => p.LastUpdated))
{
   data.Add(new List<string>
   {
        person.UserId,
        person.FullName,
        person.Title,
        person.SomePeople2.Any() ? "Y" : "N"
    }    
}

return Json(data, JsonRequestBehavior.AllowGet);

但如果你不想添加外键,你可以这样做

foreach (var person in _db.People.OrderByDescending(p => p.LastUpdated))
{
   data.Add(new List<string>
   {
        person.UserId,
        person.FullName,
        person.Title,
        (_db.SomePeople2.Any(x=>x.UserId == p.UserId) ? "Y" : "N")
    }    
}

return Json(data, JsonRequestBehavior.AllowGet);

UPD 规范化代码:

return Json(
    _db.People.OrderByDescending(p =>
            p.LastUpdated
        ).Select(p => 
            new
            {
                ID = person.UserId,
                Name = person.FullName,
                Title = person.Title,
                InOtherTable = _db.SomePeople2.Any(x=>x.UserId == p.UserId)
            }
        ).ToArray(),
    JsonRequestBehavior.AllowGet
);

【讨论】:

    【解决方案3】:

    您需要在此实体和另一个表之间建立一个 LINQ/Lambda 外连接。连接后另一个表中的任何空值表示该人仅存在于第一个表中。我目前没有时间编写解决方案,但很乐意在早上这样做

    你的 Json 列表结构也是错误的。

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2018-10-23
      • 2011-08-31
      • 2011-08-26
      • 2021-06-05
      • 1970-01-01
      • 2014-10-02
      • 2019-08-04
      • 2021-01-07
      相关资源
      最近更新 更多