[英]How to Convert Anonymous Type to List <dynamic> using Linq to SQL in C#
[英]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.