我在一个模型中有多个表的类,如下所示:
public partial class Nurse
{
public long Id { get; set; }
public Nullable<System.Guid> Guid { get; set; }
public long UserId { get; set; }
public string Name {get;set;}
public User user {get;set;}
}
我想像这样使用join用所有详细信息填充Nurse类的所有数据。
public List<Nurse> GetCareNurses(int id)
{
var result = (from r in _context.Nurses
join u in _context.Users on r.UserId equals u.Id
where r.sector_id == id
select new Nurse { UserId = r.UserId, Name=u.FirstName+" " +u.LastName }).ToList();
return result.ToList();
}
它应该仅填充我在两个表中都需要的2个字段的数据,但会以The entity or complex type 'WatsonModel.Nurse' cannot be constructed in a LINQ to Entities query.
的形式抛出错误。
答案 0 :(得分:0)
您不能投影到映射的实体(护士),但是可以投影到匿名类型或数据传输对象(DTO)来传递数据。
如果您创建NurseDTO:
public class NurseDTO
{
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
然后致电GetCareNurses:
//Change 1: Change your List to List of type NurseDTO
public List<NurseDTO> GetCareNurses(int id)
{
var result = (from r in _context.Nurses
join u in _context.Users on r.UserId equals u.Id
where r.sector_id == id
//Change 2: Select new NurseDTO
select new NurseDTO { UserId = r.UserId, Name=u.FirstName+" " +u.LastName }).ToList();
return result.ToList();
}
您应该返回NurseDTO列表