【问题标题】:Linq query in ASP.net MVC accessing another table through a tableASP.net MVC中的Linq查询通过表访问另一个表
【发布时间】:2014-06-17 11:49:14
【问题描述】:

我正在尝试通过另一个表访问一个表中的值。我有一个包含 PainCategoryId 的表 PainCategories 和一个包含 PainCategoryId 的表 Triage。我正在尝试通过 Triage 运行查询,以将该 Id 值与 PainCategory 表中的值进行比较。分类表包含多个 PainCategoryId 为 1 的行,并且在 PainCategory 表中只有一个 PainCategoryId = 1。如果有人可以提供帮助,将不胜感激。

这是我的控制器中的 linq:

 tt.painCats = db.PainCategories.ToList().Where(p => p.CompanyId == CompanyId);

tt.triages = db.Triages.ToList().Where(t => t.PainCategoryId == tt.painCats.
Contains(t.PainCategoryId)); //Error is in this line because it is just not done
//right with the Contains.

分类模型:

public class Triage
    {
        public int Id { get; set; }
        public string Status { get; set; }
        public int PainCategoryId { get; set; }

        public virtual PainCategory PainCategory { get; set; }
    }

PainCategory 模型:

public class PainCategory
    {
        public PainCategory()
        {
            Triages = new HashSet<Triage>();
        }
        public int PainCategoryId { get; set; }
        public string Title { get; set; }

        public virtual ICollection<Triage> Triages { get; set; }
    }

查看剃须刀呼叫:

foreach (var item in Model.painCats)
        {
            @Html.Label(item.Title)<br/>
            foreach(var tri in Model.triages)
            {
                @Html.RadioButton(tri.PainCategory.Title, tri.Order)
                @Html.Label(tri.Description)<br/>
            }
        }

【问题讨论】:

  • 向我们展示PainCatogoriesTriages 的类结构。
  • 我用模型编辑了它。
  • 所以这行得通,但它只返回所有带有 paincategory = 到 3 的分类(这就像 6 行),但我需要它来返回那些 = 到 2 和 1。
  • tt.triages = db.Triages.ToList().Where(t => t.PainCategoryId == tt.painCats.Select(x => x.PainCategoryId).FirstOrDefault());

标签: c# mysql asp.net sql linq


【解决方案1】:

肖恩,

你可以试试

// This doesn't work because db.Triages is not List<T>, 
// the Contains method only applies to Lists
tt.triages = db.Triages.ToList().Where(t => tt.painCats.Contains(t.PainCategoryId));

更新:

尝试使用 Any 运算符,如下所示:

// The Any method is a core linq method and is implemented for both Enumerable and Queryable
tt.triages = db.Triages.ToList().Where(t => tt.painCats.Any(cat => t.PainCategoryId == cat.PainCategoryId));

【讨论】:

  • 表示 IEnumerable' 不包含“包含”的定义和最佳扩展方法重载...
  • 这非常适合从数据库中获取每个paintcategoryId。我编辑了代码,我试图打印出一个 painCategory 标题,然后是该标题下的 PaincategoryId,然后是下一个带有该标题 PaintCategoryId 的 PainCategory 标题。有什么想法吗?
  • 为什么不用你的视图模型代码打开另一个问题?这将更易于查看,并使此问题对将来的参考更有用。
猜你喜欢
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-19
  • 1970-01-01
相关资源
最近更新 更多