在Linq to Entity中选择2列值的问题

时间:2011-06-21 09:25:30

标签: entity-framework linq-to-sql asp.net-mvc-2 linq-to-entities

您好我正在尝试选择两列的值,这是第二个驱动程序和价格,但我收到错误:无法将类型'System.Linq.IQueryable'隐式转换为'System.Linq.IQueryable'。存在显式转换(您是否缺少演员?)

以下是代码:

 public IQueryable<Event> GetSecondDriverOption(int eventID)
 {
     ApextrackdaysEntities entity = new ApextrackdaysEntities();
     IQueryable<Event> SecondDriver = from p in entity.Events
                                      where p.ID == eventID
                                      select new{ p.SecondDriver,
                                                  p.SecondDriverPrice};
     return SecondDriver;
 }

任何帮助或建议都将受到赞赏thnx

2 个答案:

答案 0 :(得分:3)

如果IQueryable<Event> Event是您的映射类型,则无法使用投影。您必须选择Event

IQueryable<Event> SecondDriver = from p in entity.Events
                                 where p.ID == eventID
                                 select p;

或者您必须将新类型和项目数据创建为新类型:

public class EventDto
{
    public Driver SecondDriver { get; set; }
    public Price SecondDriverPrice { get; set; }
}

并重新定义您的方法:

public IQueryable<EventDto> GetSecondDriverOption(int eventID)
{
    ApextrackdaysEntities entity = new ApextrackdaysEntities();
    IQueryable<EventDto> SecondDriver = from p in entity.Events
                                        where p.ID == eventID
                                        select new EventDto 
                                            {
                                                SecondDriver = p.SecondDriver,
                                                SecondDriverPrice = p.SecondDriverPrice
                                            };
    return SecondDriver;
}

答案 1 :(得分:1)

您无法返回匿名对象。试试这样:

public IQueryable<Event> GetSecondDriverOption(int eventID)
{
    ApextrackdaysEntities entity = new ApextrackdaysEntities();
    var seconDriver = 
           from p in entity.Events
           where p.ID == eventID;
           select p;
    return secondDriver;
}