2017-04-04 157 views
0

試圖返回實體選定字段,但得到的錯誤無法隱式轉換類型「System.Collections.Generic.List」到「System.Collections.Generic.List <Model.Room

我的接口

public interface IRoomRepository 
{ 
    List<Room> All(); 

    Room Get(int id); 

    Room Add(Room obj); 


    void Delete(Room obj); 

    void Update(Room obj); 
} 

我的倉庫,我實現IRoomRepository

public List<Room> All() 
    { 
     using (HotelEntities db = new HotelEntities()) 
     { 
      var result = from room in db.Rooms 
         select new 
         { 
          room.RoomNumber, 
          room.Id, 
          room.RoomType 
         }; 
      return result.ToList(); 
     } 
    } 

收到以下錯誤

無法隱式轉換類型 'System.Collections.Generic.List <>' 到 'System.Collections.Generic.List'

編輯

房型號

namespace Model 
{ 
    using System; 
    using System.Collections.Generic; 

    public partial class Room 
    { 
     public int Id { get; set; } 
     public string RoomNumber { get; set; } 
     public Nullable<int> RoomTypeId { get; set; } 
     public Nullable<int> RoomStatusId { get; set; } 

     public virtual RoomStatus RoomStatus { get; set; } 
     public virtual RoomType RoomType { get; set; } 
    } 
} 
+0

你所有的()方法返回一個非客房類型其只能從房間返回3個屬性,並非所有的 – BugFinder

回答

1

你必須創建Room明確地對象。 new {}將創建無法轉換爲Room的匿名對象。假設屬性名稱是相同的,下面應該工作

public List<Room> All() 
{ 
    using (HotelEntities db = new HotelEntities()) 
    { 
     var items = from room in db.Rooms 
        select new 
        { 
         room.RoomNumber, 
         room.Id, 
         room.RoomType 
        }.ToList(); 

     var result = items.Select(i=> 
         new Room { 
         RoomNumber = i.RoomNumber, 
         Id = i.Id, 
         RoomType = i.RoomType 
        }).ToList(); 
     return result; 
    } 
} 
+0

室得到這個:無法初始化類型「房間」與一個集合初始值設定項,因爲它沒有實現'System.Collections.IEnumerable' – rilly009

+0

@ rilly009你可以發佈'Room'類的定義嗎? – tchrikch

+0

消息=實體或複雜類型'hotelPlusModel.Room'不能在LINQ to Entities查詢中構造。 – rilly009

相關問題