ASP.NET实体框架SqlQuery无法正常工作

时间:2016-10-20 22:05:59

标签: c# asp.net entity-framework

我有一个SQL查询,当我在SQL Server中运行它时,它可以正常工作。现在我想将此查询与实体框架一起使用,如下所示:

ViewBag.TimeSlots = dbTimeSlots.Data.SqlQuery("SELECT a.id, concat(a.dateSlot, ' - ', a.timeSlot) as dateTimeSlot, sum(IIF(b.dateSlot is null,0,1)) as counter FROM VIP_Preview_TimeSlots as a LEFT OUTER JOIN [CP-VIP-Preview] as b ON a.dateSlot = b.dateSlot AND a.timeSlot = b.timeSlot GROUP BY a.timeSlot, a.dateSlot, a.[order], a.id Having sum(IIF(b.dateSlot is null,0,1)) < 30 ORDER BY a.[order]").ToList();

然而,当我运行它时,我收到此错误:

The data reader is incompatible with the specified ‘CP.Models.VIP_Preview_TimeSlots'. A member of the type, 'timeSlot', does not have a corresponding column in the data reader with the same name.

这是我的班级:

public class VIP_Preview_TimeSlots
    {
        public int id { get; set; }
        [DisplayName("Time Slots")]
        public string timeSlot { get; set; }
        [DisplayName("Date Slots")]
        public string dateSlot { get; set; }
        public int order { get; set; }
    }

    public class VIPPreviewTimeSlots : DbContext
    {
        public DbSet<VIP_Preview_TimeSlots> Data { get; set; }
    }

我真的不知道为什么这不起作用,查询有效,我不知道为什么Entity Framework有问题,我该如何解决这个问题?

即使我尝试一个简单的查询:

ViewBag.TimeSlots = dbTimeSlots.Data.SqlQuery("SELECT id, concat(dateSlot, ' - ', timeSlot) as dateTimeSlot FROM VIP_Preview_TimeSlots").ToList();

我得到了同样的错误。

3 个答案:

答案 0 :(得分:0)

您的SQL查询不会将dateSlottimeSlot作为单个列返回,而是将它们dateSlot + ' - ' + timeSlot连接为dateTimeSlot

调整SQL查询
concat(a.dateSlot, ' - ', a.timeSlot) as dateTimeSlot

为:

a.dateSlot, a.timeSlot

删除您的timeSlotdateSlot媒体资源,并将其替换为dateTimeSlot媒体资源。

答案 1 :(得分:0)

您有iddateTimeSlotcounter作为查询返回的列,不是timeSlot

答案 2 :(得分:0)

实体框架代码正在寻找一个时间段属性,这在您的选择查询中似乎没有。