我在模型中有一个 BookingView 类:
public class BookingView
{
[Required]
[Display(Name = "Attraction")]
public int Attraction { get; set; }
[Required]
[Display(Name = "Date")]
public string Date { get; set; }
[Required]
[Display(Name = "Username")]
public string Username { get; set; }
}
数据库中针对此模型的表是Tickets。
我需要在名为 BookingManager 的模型中的另一个类中编写一个函数来获取所有票务记录。
public IEnumerable<BookingView> GetAllBookings()
{
var a = from o in dre.Tickets select o;
return a.ToList();
}
我想在名为 ViewAllBookings 的 View 中显示这些记录:
@model IEnumerable<VirtualTickets.Models.ViewModel.BookingView>
@{
ViewBag.Title = "ViewAllBookings";
}
<h2>ViewAllBookings</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Attraction
</th>
<th>
Date
</th>
<th>
Username
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Attraction)
</td>
<td>
@Html.DisplayFor(modelItem => item.Date)
</td>
<td>
@Html.DisplayFor(modelItem => item.Username)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
该函数在函数 GetAllBookings 的返回语句中给出了编译时间错误。如果我将返回类型更改为 Ticket,那么我会按预期收到运行时错误,因为在 View ViewAllBookings 中,它需要具有 BookingView 类型的 IEnumerable 记录列表。
请提供针对这种情况的解决方案。我真的很困惑如何处理这个问题。
谢谢
请您参考如下方法:
看起来您的设置需要将实体类 Ticket 转换为 View 模型 BookingView。我猜你需要这样的东西:
return a.AsEnumerable().Select(ticket => new BookingView
{
Attraction = ticket.SomeProperty,
// etc
})
.ToList();
