我有2個表Job_table
和Employee_table
。我想在Employee_table
的索引視圖中顯示來自Job_table
的emp_id
和來自Employee_table
的對應emp_name
。從不同的表中取數據並將其顯示在查看索引中
對於這個問題,我創建一個ViewModel EmployeeViewModel
並將我的行爲結果的索引視圖與IEnumerable<EmployeeViewModel>
綁定。對於EmployeeViewModel的定義是這樣的:
public class EmployeeViewModel
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string JobName { get; set; }
//..Other memberVariables..
}
我的模型:
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string Address { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
}
,工作臺,更名爲工作爲自己的方便:
public class Job
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int JobId { get; set; }
public string JobName { get; set; }
public JobCategory JobCategory { get; set; }
public int EmployeeId { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
在我的索引行動,我通過連接兩個表創建結果集,將其綁定到IEnumerable<EmployeeViewModel>
並將其作爲模型傳遞給視圖。該視圖應接收IEnumerable<EmployeeViewModel>
正如我前面提到類型的模型,所以我需要查詢我的實體應該是這樣的:
public ActionResult Index()
{
//..something like this..this is IQueryable..
//...convert this to IEnumerable and send this as the model to ..
//..the Index View as shown below..here you are querying your own tables,
//.. Employee and Job,and binding the result to the EmployeeViewModel which
//.. is passed on to the Index view.
IEnumerable<EmployeeViewModel> model=null;
model = (from c in db.Employees
join q in db.Jobs on c.EmployeeId equals q.EmployeeId
from q in jobs.DefaultIfEmpty()
group new { q, c } by c into grp
select new EmployeeViewModel
{
EmployeeId = grp.Key.EmployeeId,
EmployeeName = grp.Key.EmployeeName,
});
return View(model);
}
我想顯示類似的結果:
|Employee 1|
|----------|
| Job 1 |
| Job 2 |
|Employee 2|
|----------|
| Job 3 |
| Job 4 |
| Job 5 |
但現在我的結果是
|Employee 1| |Employee 1|
|----------| |----------|
| Job 1 | | Job 2 |
|Employee 2| |Employee 2| |Employee 2|
|----------| |----------| |----------|
| Job 3 | | Job 4 | | Job |
如何刪除重複項?
謝謝你們,它的工作原理。但是當我插入2行與同僱員,看來下面 employee1 JOB1 employee1 作業2 ,我想只有employee1是負載,我怎麼能做到這一點,我認爲它看起來像不同?請非常感謝你 – user3544501
'employee1 be load'是什麼意思?你在你的問題中說'我想顯示兩個員工'。感謝你們, – pasty
顯示都是工作。但是,當我插入2行與EmployeeId相同,它出現在employee1 job1 employee1 job2下面,我想只有employee1被加載,我怎麼能做到這一點,我認爲它看起來像不同?請非常感謝你 – user3544501