【问题标题】:LINQ query with variable带有变量的 LINQ 查询
【发布时间】:2017-12-21 17:58:07
【问题描述】:

大家好,我正在尝试使用以下代码在 .NET MVC 中的 C# 中的 LINQ 中进行查询:

public int Delete(int id)
        {
            using (DBEntities db = new DBEntities())
            {
                var student = db.Students.Find(id);
                var curso = from t in db.Teachers
                            join i in db.Inscriptions on id equals i.StudentId
                            where t.Id == i.StudentId
                            select i.Id;
                var atten = from a in db.Attendances
                            where a.InscriptionId == curso
            }
        }

我正在尝试将我正在执行的查询与已包含值的变量进行比较。 我想比较一下:where a.InscriptionId == curso Curso 是包含我需要比较的值的变量。

我该怎么做?

【问题讨论】:

  • curso 的值类型可能需要转换为整数(或您尝试比较的任何数据类型)。 where a.InscriptionId == (int)curso
  • curso 从查询中返回 IEnumerable<>,不管你知道它只会有 0 或 1 个元素。所以你需要做类似var cursoId = curso.FirstOrDefault() 然后使用 cursoId 代替
  • @NSGaga 你应该发表你的评论作为答案。
  • @NetMage 我猜你是对的。

标签: c# asp.net asp.net-mvc linq


【解决方案1】:

你不能使用另一个连接并将两者都作为一个对象返回吗?类似...

var student = db.Students.Find(id);
var CursoAndAtten = (from t in db.Teachers
                        join i in db.Inscriptions on i.id equals i.StudentId
                        join a in db.Attendances on a.InscriptionId equals 
                        i.Id
                        where t.Id == i.StudentId
                        select new { curso = i.Id, atten = a}).ToList()// Or e.g FirstOrDefault() ;

【讨论】:

    【解决方案2】:

    您的查询将返回类型 IEnumerable<int> 而不是 int。

    尝试使用FirstOrDefault() 选择查询末尾的单个元素。

    public int Delete(int id)
        {
            using (DBEntities db = new DBEntities())
            {
                var student = db.Students.Find(id);
                var curso = from t in db.Teachers
                            join i in db.Inscriptions on id equals i.StudentId
                            where t.Id == i.StudentId
                            select i.Id;
                var atten = from a in db.Attendances
                            where a.InscriptionId == curso.FirstOrDefault() //this line was modified
            }
        }
    

    【讨论】:

    • Try casting as an integer ?我的意思是你只是把所有的 cmets 编译在一起吗? :)
    【解决方案3】:

    您的cursoIEnumerable<>(因为这是查询返回的内容),无论您知道它只会有0 或1 个元素。

    你可以做类似的事情

    var cursoId = curso.FirstOrDefault() 
    

    然后改用cursoId

    注意:您可能应该测试和处理default,当没有返回任何元素时,避免进入下一个查询,我猜是做其他事情。

    还有一个建议,只需将光标悬停在 var 变量上即可查看其实际类型。

    【讨论】:

      猜你喜欢
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多