LINQ查询带变量

问题描述 投票:0回答:3

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

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是包含我需要比较的值的变量。

我怎样才能做到这一点 ?

c# asp.net asp.net-mvc linq
3个回答
0
投票

你能不能使用另一个连接并将它们作为对象返回?就像是...

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() ;

0
投票

您的查询将返回类型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
        }
    }

0
投票

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

你可以做点什么

var cursoId = curso.FirstOrDefault() 

然后使用cursoId代替。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.