TestzWCh TestzWCh - 1 month ago 17
C# Question

Unable to create a constant value of type. While trying to match data from viewmodel to context

Im trying to get selected devices from view and match them with the devices in context but i only get the following Unable to create a constant value of type

ViewModels.XXXViewModel
. Only primitive types or enumeration types are supported in this context.

public ActionResult TransferDevices(IList<XXXViewModel> viewModel)
{
var selected = viewModel.Where(x => x.isSelected).ToList();
IQueryable<Device> devicesQueryable = _db.Devices;

var devices = devicesQueryable.Where(x => selected.Any(y => y.Id == x.Id)).ToList() ;
}

Answer

I suspect you should make selected a list of IDs... then you can just use Contains:

public ActionResult TransferDevices(IList<XXXViewModel> viewModel)
{
    var selected = viewModel.Where(x => x.isSelected)
                            .Select(x => x.Id)
                            .ToList();
    IQueryable<Device> devicesQueryable = _db.Devices;

    var devices = devicesQueryable.Where(x => selected.Contains(x.Id)).ToList();
}

I'd expect that to work... it's certainly easier for the LINQ provider to translate.