1

モデルに 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; }
}

DB のこのモデルに対するテーブルはTicketsです。

BookingManagerすべてのチケット レコードを取得するには、という名前のモデルの別のクラスに関数を記述する必要があります。

public IEnumerable<BookingView> GetAllBookings()
{
    var a = from o in dre.Tickets select o;
    return a.ToList();
}

これらのレコードを という名前のビューに表示したいViewAllBookings:

@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、return ステートメントの関数でコンパイル時エラーを返します。戻り値の型を に変更すると、期待どおりTicketにランタイム エラーが発生します。ViewAllBookingsBookingView

この状況の解決策を教えてください。私はこれにどう対処するか本当に混乱しています。

ありがとう

4

4 に答える 4

1

Ticket を BookingView にマップするメソッドを作成し、次のように使用する必要があります。

public IEnumerable<BookingView> GetAllBookings()
{
    var a = from o in dre.Tickets select o;
    return a.AsEnumerable().Select(Map).ToList();
}

private BookingView Map(Ticket ticket)
{
    var bookingView = new BookingView();
    //mapping code goes here
    return bookingView;
}
于 2013-07-19T19:49:45.897 に答える
1

Ticketsテーブルに実際にコード内のクラスと同じ列があるかどうBookingViewかはわかりませんが、テーブルとクラスの間にマッピングがある場合、解決策は次のようになります。

var a = from o in dre.Tickets 
         select new BookingView  { Attraction= o.Attraction, 
                                   Date=o.Date, 
                                   Username = o.UserName } ;
return a.ToList();
于 2013-07-19T19:54:55.433 に答える