尝试返回实体选定字段但收到错误
我的界面
public interface IRoomRepository
{
List<Room> All();
Room Get(int id);
Room Add(Room obj);
void Delete(Room obj);
void Update(Room obj);
}
My Repository我实现了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();
}
}
获得以下错误
无法隐式转换类型&#39; System.Collections.Generic.List&lt;&gt;&#39;到&#39; System.Collections.Generic.List&#39;
修改
房间模型类
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 :(得分: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;
}
}