简体   繁体   中英

MVC-How to Join Two Tables or Models using Linq ASP.NET MVC?

I am working with asp.NET MVC . And I am trying to find Salary Grades of employees [as we find in oracle 12c using scott schema]. I have created 4 Models EMP, DEPT, Bonus, and SalGrade (Same as scott schema in oracle 12c) . The query for finding grades in Oracle-12c is following.

SELECT s.grade, count(*), max(sal)
 FROM EMP e, SalGrade s
   WHERE e.sal BETWEEN s.LoSal AND s.HiSal
     GROUP BY s.grade;

I just need to convert the above given query into ASP.NET MVC LINQ query.

Models I have created are follwing.

Dept Models:

public class Department{
[Key]
public int Deptno { get; set; }
public string Dname { get; set; }
public string  Loc { get; set; }}

EMP Model:

 public class Employee
{
    [Key]
    public int Empno { get; set; }
    public string  Ename { get; set; }
    public string Job { get; set; }
    public int Mgr { get; set; }
    public DateTime Hiredate { get; set; }
    public int Sal { get; set; }
    public int Comm { get; set; }
    public int Deptno { get; set; }
    public Department Department { get; set; }

}

SalGrade Model

public class Salgrade
{
    [Key]
    public int Grade { get; set; }
    public int LoSal { get; set; }
    public int HiSal { get; set; }
}

In your controller class method, you might have some code like this:

using(var db = new DepartmentEntities()){

    var query = from db.Employee, db.Salgrade
                where db.Employee.Sal between db.Salgrade.LoSal and db.Salgrade.HiSal
                group by db.Salgrade.Grade
                select new { db.Salgrade.Grade, count(*), max(db.Employee.Sal) };

    // Use query results in a foreach loop or whatever...
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM