Reputation: 96
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; }
}
I am joining these two tables.
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 });
and I am sorting these result set using the below code.
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);
Till now it is working as expected. Finally, I want to convert it to 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();
While converting to Gateway
, it is throwing the error:
The entity or complex type 'Models.Context.Gateway' cannot be constructed in a LINQ to Entities query.
Upvotes: 0
Views: 258
Reputation: 745
In Linq-to-Entities you can only project to an anonymous type or a regular class. You can't project to an existing entity type. You can with linq-to-objects like so
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();
I didnt test this one,Please do comment after try this one.then i can help you to get your answer.
Upvotes: 3