這似乎很“初學者”,但我很掙扎。
我有一個連接兩個表(Employee和Cars)的 SQL Server 視圖。我有這個觀點的模型。
當我打開 SQL Server Management Studio 并使用Select *與員工 A 匹配的記錄查詢 SQL Server 視圖時,我得到了兩條記錄,因為該員工在表中列出了一次,在Employee表中列出了兩次Cars。在 SQL Server Management Studio 中,我Cars為所說的人驗證這兩個是唯一的。應該是這樣。
但是我必須在 ASP.NET MVC 5 應用程式中的代碼中做錯了什么,因為當我加載Index視圖時,它應該顯示兩個唯一的記錄 - 它反而向我顯示了完全相同的記錄(同一輛車)兩次。
在我的控制器中:
public ActionResult Index()
{
string MyName =
System.Security.Principal.WindowsIdentity.GetCurrent().Name;
String result = MyName.Substring(MyName.Length - 6);
ViewBag.WhoAmI = result;
UserPrincipal userPrincipal = UserPrincipal.Current;
String name = userPrincipal.DisplayName;
ViewBag.MyRealID = name;
try
{
Web_Parkinglot_Header_FullViewRepository oItem = new
Web_Parkinglot_Header_FullViewRepository();
Var item = oItem.GetbyLogon((string)result);
if (!String.IsNullOrEmpty(result))
{
}
return View(item.ToList());
}
catch (Exception ex)
{
throw ex;
}
}
存盤庫:
public List<Web_Parkinglot_Header_FullView> GetbyLogon(string result)
{
return this.Context.Web_Parkinglot_Header_FullViews.Where(a => a.logon_id == result).ToList();
}
看法:
foreach (var item in Model)
{
<table class="table">
<tr>
<td>
<img src="~/Content/images/bmw.png" width="75" height="50" />
</td>
<td>
<b>Vehicle Make:</b> @Html.DisplayFor(modelItem => item.veh_make)
</td>
<td>
<b>Model:</b> @Html.DisplayFor(modelItem => item.veh_model)
</td>
<td>
<b>Color:</b> @Html.DisplayFor(modelItem => item.veh_color)
</td>
<td>
<b>Plate:</b> @Html.DisplayFor(modelItem => item.veh_plate)
</td>
</tr>
</table>
}
What I don't understand is: why, when I query the SQL Server view directly, I get the correct 2 vehicles for logon_id = A. But when I run the same query via the repository, I get 2 records, but it's the same record twice, in the foreach loop.
The SQL Server view is an inner join. I can also post more info (Model, etc if needed)
uj5u.com熱心網友回復:
從物體框架中使用視圖時存在一個微妙的問題。
如果您有一個表,請務必將其與 EF 一起使用,您需要有一個主鍵來唯一標識每一行。通常,這是一個單一的列,例如一個ID或類似的東西。
使用視圖,您沒有“主鍵”的概念 - 視圖僅包含來自某些表的某些列。
因此,當 EF 映射視圖時,它找不到主鍵 - 因此,它將使用視圖中的所有不可為空的列作為“替代”主鍵。
我不知道您的情況是什么-您應該能夠從.edmx模型中看出。
所以問題真的是你不能在視圖上有明確的主鍵。
最簡單的解決方案是僅包含視圖定義中涉及的兩個表中的主鍵(即使您不想顯示它們)。
這樣,這些將在視圖中,并且它們將不可為空,因此您應該沒問題并且不會得到任何重復。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/441800.html
