簡體   English   中英

將匿名類型轉換為列表 <T> 在C#中使用Linq到SQL

[英]Convert Anonymous Type to List <T> using Linq to SQL in C#

我正在使用帶有Linq to SQL的MVC 4,並且在我的控制器類中,我打算從具有多個表的查詢中獲取一個List並將其顯示為視圖,其中M是模型類:

在控制器中我有這個

 public List<HomeViewModel> GetHomeViewModel()
    {
        dynamic ReservationDay = (from c in hutRes.Clients
                              join r in hutRes.Reservations on c.ID_Client equals r.FK_Client
                              join ht in hutRes.Hut_Types on r.FK_HutType equals ht.ID_Hut_Type
                              join tr in hutRes.Time_Reserves on r.FK_TimeReserve equals tr.ID_Time_Reserve
                              join tc in hutRes.Type_ClientIds on c.FK_TypeClientId equals tc.ID_Type_ClientId
                              where r.DateR == DateTime.Now
                              select new
                              {
                                  r.ID_Reservation,
                                  tc.ClientId,
                                  Number = c.Number_ID,
                                  c.Name,
                                  c.Phone,
                                  time = tr.TimeReserve,
                                  ReservationDate = r.DateR
                              }).ToList();

        return ReservationDay;
    }

    public ActionResult Index()
    {

        return View(GetHomeViewModel());
    }

在視圖方面,我有這個標題:

@model List<HutReservation.ViewModel.HomeViewModel>

我遇到這個錯誤:

Can not implicitly convert type 'System.Collections.Generic.List<<>f__AnonymousType4 <int,string,short,string,string,string,System.DateTime,byte,string,short,string,string>>' in 'System.Collections.Generic.List<HutReservation.ViewModel.HomeViewModel>'

有人可以幫助我嗎?

問題是您的匿名類型列表無法轉換為HomeViewModel列表。

無論如何,為什么要使用匿名類型? 只需在查詢中創建一個新的HomeViewModel實例( Select一個HomeViewModel而不是匿名類型)。

代替LINQ中的Anonymous類型使用:

select new HomeViewModel 
{
// Set class variables here...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM