MVC EF-内部联接



我检查了可能已经有答案的问题,但似乎没有一个解决我的问题:

var semesters = db.Semesters.Where(e => e.ID == semester).ToList();
var semestersbyfaculty = db.SemestersByFaculty.Where(e => e.FacultyID == id).ToList();

我如何像在SQL中执行以下操作一样内部联接这两个查询:

SELECT 
   Fac.*, Sem.SemesterText
FROM 
   SemestersByFaculty AS Fac
INNER JOIN
   Semesters AS Sem
ON
   Fac.SemesterID = Sem.ID
WHERE id
   Fac.FacultyID = id

内部联接

以下示例显示了一个简单的内部等联接。

var query = from fac in db.SemesterByFaculty
            join sem in db.Semester on fac.SemesterID equals sem.ID
            where fac.FacultyID == id
            select new { Faculty = fac, SemesterText = sem.SemesterText };

有关更多信息,请参阅如何:执行内部联接(C#编程指南(。

更新:

来自评论

型号

class MyModel {
    public MitModel.SemestersByFacul‌​ty Faculty{ get; set; }
    public string SemesterText { get; set; }
}
class MyViewModel {
    public List<MyModel> SemesterFaculties { get; set; }
}

行动:

public ActionResult SomeAction(string id) {
    var query = from fac in db.SemesterByFaculty
                join sem in db.Semester on fac.SemesterID equals sem.ID
                where fac.FacultyID == id
                select new MyModel{ Faculty = fac, SemesterTest = sem.SemesterTest };
    var viewModel = new MyViewModel { SemesterFaculties = query.ToList() };
    return View(viewModel);
}

查看

@Model MyViewModel

假设SemestersByFaculty 中有以下字段

class SemestersByFaculty
{
    string FacultyName;
    int FacultyID;
    int SemesterID;
}

注意:如果SemestersByFaculty类中有更多字段,则可以在下面的查询中在new{}中列出它们:

var query = semesters.Join(semestersbyfaculty,
                                sem => sem.ID,
                                fac => fac.SemesterID,
                                (sem, fac) =>
                                    new { facName = fac.FacultyName, facId = fac.FacultyID,semText = sem.SemesterText }).Where(e=> e.fac.FacultyId = id);

现在,你得到的是一个可枚举的。您可以对其进行迭代并检索值。它会像:

foreach (var obj in query){
   Console.writeln("{0}-{1}-{2}",obj.facName,obj.facId,obj.semText);
}

以下是使用非LINQ语法的解决方案。此外,您还可以在"db.Semesters"one_answers"db.SomestersByFaculty"传递到"join"之前对它们执行"Where"筛选。

var result = db.SemestersByFaculty
  .Where(
    x_ => x_.FacultyID == id)
  .Join(
    db.Semesters.Where(x_ => x_.ID == semester), 
    x_ => x_.SemesterID, 
    x_ => x_.ID, 
    (x_, y_) => new 
    { 
      FacultyID = x_.ID, 
      SemesterID = y_.SemesterID,
      Sem = y_.SemesterText 
    })
  .ToList();

相关内容

  • 没有找到相关文章

最新更新