Skip to main content
 首页 » 编程设计

c#之在 C# 中使用 Linq to SQL 将匿名类型转换为列表 T>

2024年02月13日15cmt

我正在使用带有 Linq to SQL 的 MVC 4,在我的 Controller 类中,我打算从具有多个表的查询中获取一个列表,并将其作为一个列表显示在 View 中,其中 M 是一个模型类:

在 Controller 中我有这个

 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()); 
    } 

在 View 端我有这个标题:

@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>' 

任何人都可以帮助我我真的被困在这里:(

请您参考如下方法:

在 LINQ 中使用匿名类型:

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