我有這兩個表,一個是檔案,一個是照片。因此,用戶可以向資料庫添加一個檔案或一張圖片。當從資料庫中檢索資料時,我使用了一個聯合查詢。這是我使用的SQL查詢
SELECT D.* FROM Documents D
WHERE D.AddedBy = 'John'/span>
聯合
SELECT P.* FROM Photos P
WHERE P.AddedBy = 'John'
我需要把這個轉換為Linq。
var p = (from docin _context.Documents
where doc.AddedBy == LogonUsername
select doc.DocumentName).union
(from pho in _context.Photos
where pho.AddedBy == LogonUsername
select pho.PhotoName).ToList()。
Linq查詢作業正常。當我把它傳遞給視圖時,它給了我這個錯誤。
傳入字典的模型專案是型別System.Collections.Generic.List`1[System.Collections.Generic.List`2]。 Generic.List`1[System.String]',但是這個字典需要一個'System.Collections.Generic.IEnumerable`1[Document_Management_System.Models.Document]'的模型項。
我認為我所使用的模型是錯誤的。
這就是控制器
public ActionResult Test()
{
var p = (from doc in _context.Documents
where doc.AddedBy == LogonUsername
select doc.DocumentName).union
(from pho in _context.Photos
where pho.AddedBy == LogonUsername
select pho.PhotoName).ToList()。
return View(p);
視圖
@model IEnumerable< Document_Management_System.Models.Document>
@{
ViewBag.Title = "Test"。
}
<h2>測驗</h2>
<div class="panel-body">
<table class="zebra">
<tr>
<th>@Html.DisplayNameFor(model => model.DocumentName)</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DocumentName)
</td>
</tr>
}
</table>
</div>
請幫助我解決這個問題。謝謝你。
uj5u.com熱心網友回復:
你已經做了
return View(p);
而p是一個List<string>(由于你的LINQ查詢選擇了一個單一的字串,并將其與另一個單一字串的選擇聯合起來),但你答應視圖它將收到一個
@model IEnumerable< Document_Management_System.Models.Document>
Document不是一個字串(不是一個Document)。你需要重塑你的LINQ,使它產生一個Document的列舉。現在,它得到了一堆Document的名字(一個字串):
select doc.DocumentName
還有一堆照片的名字......
select pho.PhotoName
并將它們聯合起來
總的來說,你最終可能會做一個并聯,而不是聯合,但主要是你可能需要調整查詢,以便將照片轉換為檔案。當然,除非名字的串列適合你的目的,100%,在這種情況下,調整你的@model宣告,以承諾一個IEnumerable<string>
就個人而言,我認為我會有一個全新的類,而不是檔案,它追蹤照片和檔案之間的共同屬性(名稱、用戶創建、上傳日期、大小、批準、資料庫中的標識),再加上一個可列舉項,說明它是照片還是檔案(如果這對在 Ui 中顯示不同的圖示很重要),我將承諾一個 @model,它是 那個新類的可列舉項,稱之為 FileViewModel 或其他。
uj5u.com熱心網友回復:
只需修復你的模型和視圖項
@model List<string>
<th> 照片名稱</th>
</tr>
@for (var i=0; i<Model.Count; i )
{
<tr>
<td>
@Html.DisplayFor(model => model[i])
</td>
</tr>
}
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/327594.html
標籤:
上一篇:Vue獲取資料時,查詢引數不作業
