public class Gateway : ModelBase
{
public int Id { get; set; }
public int SystemGroupId { get; set; }
public string DeviceName { get; set; }
public string MacAddress { get; set; }
public bool Enabled { get; set; }
}
public class SystemGroup : ModelBase
{
public int Id { get; set; }
public string Name { get; set; }
}
我正在加入这两张桌子。
var Query = (from g in dbContext.Gateways
join s in dbContext.SystemGroups on g.SystemGroupId equals s.Id
select new {
Id = g.Id,
SystemGroupId = g.SystemGroupId,
SystemGroupName = s.Name,
DeviceName = g.DeviceName,
MacAddress = g.MacAddress,
DeviceType = g.DeviceType,
Enabled = g.Enabled });
我正在使用以下代码对这些结果集进行排序。
if (sortParameter == Resources.ViewResources.Views.SystemGroup)
Query = Query.OrderBy(x => x.SystemGroupName);
else if (sortParameter == Resources.ViewResources.Views.DeviceName)
Query = Query.OrderBy(x => x.DeviceName);
else
Query = Query.OrderBy(x => x.Id);
直到现在它按预期工作。最后,我想将其转换为Gateway
。
return Query.Select(x => new Gateway {
Id= x.Id,
SystemGroupId = x.SystemGroupId,
DeviceName = x.DeviceName,
MacAddress=x.MacAddress,
DeviceType= x.DeviceType,
Enabled= x.Enabled}).ToList();
转换为Gateway
时,会抛出错误:
实体或复杂类型' Models.Context.Gateway'不能在LINQ to Entities查询中构造。
答案 0 :(得分:3)
在Linq-to-Entities中,您只能投射到匿名类型或常规类。您无法投影到现有实体类型。您可以使用linq-to-objects这样
return Query.Select new {
Id= x.Id,
SystemGroupId = x.SystemGroupId,
DeviceName = x.DeviceName,
MacAddress=x.MacAddress,
DeviceType= x.DeviceType,
Enabled= x.Enabled}).AsEnumerable().Select(x => new Gateway {
Id= x.Id,
SystemGroupId = x.SystemGroupId,
DeviceName = x.DeviceName,
MacAddress=x.MacAddress,
DeviceType= x.DeviceType,
Enabled= x.Enabled}).ToList();
我没有测试过这个,请在尝试这个之后做评论。然后我可以帮助你得到答案。