C# 无法隐式转换类型“System.Linq.IQueryable<

本文关键字:IQueryable Linq anonymous type System 类型 转换 | 更新日期: 2023-09-27 18:31:51

我在 .Net 中有这段代码,但出现此错误:

C# Cannot implicitly convert type System.Linq.IQueryable<<anonymous type:..

有人可以帮我弄清楚吗?

IQueryable<Reservations> queryRes;
queryRes = (from p in ctx.Reservations
                           join a in ctx.Employees on p.Id_employee equals a.Id
                           join c in ctx.Clients on p.Id_client equals c.Id
                           orderby p.Id
                           select new
                           {
                               p.Date,
                               p.Hour,
                               c.Name,
                               c.Surname,
                               p.Email,
                               p.Phone,
                               p.Service,
                               name1=a.Nume,
                               surname1=a.Prenume
                           });
 reservationsView.Source = queryRes.ToList();

C# 无法隐式转换类型“System.Linq.IQueryable<<anonymous type:”

尝试创建一个具有任何名称的简单视图模型..."预订视图",其中包含您在"选择新建"上创建的字段...

public class ReservationsView
    {
        public System.DateTime Date{ get; set; }       
        public string Hour{ get; set; }
        public string Name{ get; set; }
        public string Surname{ get; set; }
        public string Email{ get; set; }
        public string Phone{ get; set; }
        public string Email{ get; set; }
        public string name1{ get; set; }
        public string surname1{ get; set; }
    }

然后。。。

IQueryable<ReservationsView> queryRes;
queryRes = (from p in ctx.Reservations
                           join a in ctx.Employees on p.Id_employee equals a.Id
                           join c in ctx.Clients on p.Id_client equals c.Id
                           orderby p.Id
                           select new ReservationsView
                           {
                               p.Date,
                               p.Hour,
                               c.Name,
                               c.Surname,
                               p.Email,
                               p.Phone,
                               p.Service,
                               name1=a.Nume,
                               surname1=a.Prenume
                           });

希望有帮助。

语句select new { ...创建新的匿名类型。从Reservations中选择所有内容,或创建具有所需属性的自定义类。

如前所述,选择保留而不是创建匿名对象,

        IQueryable<Reservations> queryRes;
        queryRes = (from p in ctx.Reservations
                    join a in ctx.Employees on p.Id_employee equals a.Id
                    join c in ctx.Clients on p.Id_client equals c.Id
                    orderby p.Id
                    select p);
        reservationsView.Source = queryRes.ToList();