【发布时间】:2021-12-29 22:00:40
【问题描述】:
public IEnumerable<ProfileVM> GetEmployees()
{
var register2 = from a in context.Employees
join b in context.Accounts on a.NIK equals b.NIK
select new
{
a.NIK,
b.Password,
};
return register2.ToList();
}
我有一个使用 LINQ 调用数据的存储库,我想返回它以便将它传递给我的控制器,但我无法返回它
return (IEnumerable<ProfileVM>)register2.ToList();
IDE 建议这样做,但它仍然不起作用,错误说:
System.InvalidCastException: '无法转换类型的对象 'System.Collections.Generic.List
1[<>f__AnonymousType83[System.String,System.String,System.Int32]]' 输入 'System.Collections.Generic.IEnumerable`1[API.ViewModel.ProfileVM]'。'
我的个人资料虚拟机
public class ProfileVM
{
public string NIK { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Phone { get; set; }
public string Password { get; set; }
public DateTime BirthDate { get; set; }
public int Salary { get; set; }
public string Email { get; set; }
public int GPA { get; set; }
public string Degree { get; set; }
public int UniversityId { get; set; }
}
【问题讨论】:
-
您的 Linq 查询不返回任何
ProfileVM对象:它返回一个新的匿名类型对象。ProfileVM的定义是什么? -
我已经编辑了我的问题,现在它包括 profileVM
-
你试过了吗?
select new ProfileVM { Nik = a.Nik, Password = b.Password } -
@YongShun 你的解决方案 很好解决我的问题,我不知道我们是否需要选择 ProfileVM,谢谢
-
为什么
Password是String属性?