简体   繁体   English

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

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

I'm working with MVC 4 with Linq to SQL and in my controller class I intend to obtain a List from a query that has several tables and show it into the view as a List where M is a model class: 我正在使用带有Linq to SQL的MVC 4,并且在我的控制器类中,我打算从具有多个表的查询中获取一个List并将其显示为视图,其中M是模型类:

In the controller I have this 在控制器中我有这个

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

And in the view side I have this header: 在视图方面,我有这个标题:

@model List<HutReservation.ViewModel.HomeViewModel>

I'm having this error: 我遇到这个错误:

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

Can Anybody help me I'm really stuck here :( 有人可以帮助我吗?

The problem is that a list of your anonymous type can't be converted to a list of HomeViewModel . 问题是您的匿名类型列表无法转换为HomeViewModel列表。

Why are you using an anonymous type, anyway? 无论如何,为什么要使用匿名类型? Simply create a new HomeViewModel instance in your query ( Select a HomeViewModel instead of an anonymous type). 只需在查询中创建一个新的HomeViewModel实例( Select一个HomeViewModel而不是匿名类型)。

Instead of Anonymous type in LINQ use: 代替LINQ中的Anonymous类型使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM