[英]Self join in LINQ query and return View
我正在使用LINQ Self Join Query在視圖上顯示數據。我的sql表包含一些員工詳細信息。我需要用他們的Manager Name顯示員工詳細信息,因為它是表中的ManagerID
EmpID Name ManagerID Designation Phone Address 1 Mike 3 Developer 123456 Texas 2 David 3 RM 123456 Delhi 3 Roger NULL GM 123456 Dallas 4 Marry 2 Developer 123456 NY 5 Joseph 2 Developer 123456 Singapore 7 Ben 2 Developer 123456 Mumbai 8 Steven 3 TL 123456 Banglore
我需要改變它的名字
我的代碼在控制器動作中
var emp = from m in t.Employees
join e1 in t.Employees on m.ManagerID equals e1.EmployeeID
select new { Id = m.EmployeeID ,
Name = m.Name,
Manager = e1.Name ,
Designation = m.Designation,
Phone =m.Phone ,address = m.Address };
return View(emp.Tolist());
並在視圖中
@model IEnumerable <mvc4application.models.employee>
但我收到運行時錯誤
傳遞到字典中的模型項的類型為System.Data.Objects.ObjectQuery
1[<>f__AnonymousType1
6 [System.Int32,System.String,System.String,System.String,System.Nullable1[System.Int32],System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1 [Mvc4application.Models.Employee]'1[System.Int32],System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
。] System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) 405487
關閉課程我理解這一點,因為我的觀點是使用Mvc4application.Models.Employee type
。
因為我無法將其轉換為模型類型。
我們可以在MVC中使用SQL視圖作為模型,以便我們可以在SQL中加入嗎?
您正在返回一個匿名對象,而您的視圖是強類型為IEnumerable<mvc4application.models.employee>
。
我強烈建議您編寫一個符合視圖要求的視圖模型,並在此視圖中包含您希望使用的信息:
public class EmployeeViewModel
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string ManagerName { get; set; }
public string Designation { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
然后調整您的LINQ查詢,以便將各種域EF對象投影到視圖模型中:
IEnumerable<EmployeeViewModel> employees =
from m in t.Employees
join e1 in t.Employees on m.ManagerID equals e1.EmployeeID
select new EmployeeViewModel
{
EmployeeID = m.EmployeeID ,
Name = m.Name,
ManagerName = e1.Name,
Designation = m.Designation,
Phone = m.Phone,
Address = m.Address
};
return View(employees.ToList());
最后使您的視圖強烈鍵入視圖模型:
@model IList<EmployeeViewModel>
現在您可以提供以下信息:
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Manager name</th>
<th>Designation</th>
<th>Phone</th>
<th>Address</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>@Html.DisplayFor(x => x[i].EmployeeID)</td>
<td>@Html.DisplayFor(x => x[i].Name)</td>
<td>@Html.DisplayFor(x => x[i].ManagerName)</td>
<td>@Html.DisplayFor(x => x[i].Designation)</td>
<td>@Html.DisplayFor(x => x[i].Phone)</td>
<td>@Html.DisplayFor(x => x[i].Address)</td>
</tr>
}
</tbody>
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.