Trying to return entity selected fields but getting error
My Interface
public interface IRoomRepository
{
List<Room> All();
Room Get(int id);
Room Add(Room obj);
void Delete(Room obj);
void Update(Room obj);
}
My Repository and i implemented 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();
}
}
Getting the following error
Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'System.Collections.Generic.List'
EDIT
Room Model Class
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; }
}
}
You have to create Room
object explicitely.new {}
creates anonymous object that can't be converted to Room
. Assuming property names are the same, following should work
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;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments