C# 无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List
试图返回实体所选字段,但出现错误 我的界面C# 无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List,c#,entity-framework,linq-to-entities,C#,Entity Framework,Linq To Entities,试图返回实体所选字段,但出现错误 我的界面 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()
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; }
}
}
您必须明确地创建房间对象。新建{}将创建无法转换为房间的匿名对象。假设属性名称相同,下面的操作应该有效
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;
}
}
您的All方法返回的是非文件室类型,它仅从文件室返回3个属性,并非所有roomgetting this:无法使用集合初始值设定项初始化类型“Room”,因为它未实现“System.Collections.IEnumerable”@rilly009是否可以发布Room类的定义?Message=无法在LINQ to Entities查询中构造实体或复杂类型“hotelPlusModel.Room”。在这种情况下,可以使用匿名查询和转换结果中的对象,请参见编辑的代码我仍然在这方面遇到错误。是否没有其他方法从实体返回中排除某些字段