我检查了可能已有答案的问题,但似乎没有一个问题解决了我的问题:
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
答案 0 :(得分:7)
以下示例显示了一个简单的内部等值连接。
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 };
有关详细信息,请参阅How to: Perform Inner Joins (C# Programming Guide)。
更新:
来自评论
模型
class MyModel {
public MitModel.SemestersByFaculty 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
答案 1 :(得分:4)
假设您在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);
}
答案 2 :(得分:2)
这是非LINQ语法的解决方案。您也可以在'db.Semesters'和'db.SemestersByFaculty'上执行'Where'过滤器,然后再将它们传递到'join'。
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();