King_Fisher King_Fisher - 3 months ago 34
C# Question

Cannot implicitly convert type 'System.Collections.Generic.List to class properties in C#

Model:

public class DataResult<T>
{
public List<T> ViewResults;
}

public class oGateEntryViewModel
{
public DataResult<GateEntryModels> oListGateEntryModels { get; set; }
}


Controller:

GateEntryViewModel oGateEntryViewModel = new GateEntryViewModel();
IGateEntryBC oIGateEntryBC = new GateEntryBC();
oGateEntryViewModel.oListGateEntryModels = oIGateEntryBC.oGetGateEntryData(); --Error
return View(oGateEntryViewModel);

oIGateEntryBC.oGetGateEntryData(); -> This method is returning the list Results.


public List<GateEntryModels> oGetGateEntryData()
{
DataAdapters oDataAdapters = new DataAdapters();
List<DataParameters> oListparams = new List<DataParameters>();
DataParameters oDataparam;
oDataparam = new DataParameters("@TYPE", SqlDbType.Int, (Int32)GateEntryEntities.EnumGateEntry.GateEntryList);
oListparams.Add(oDataparam);
DataTable dtList= oDataAdapters.GetData<DataTable>(oListparams, "PROC_GATEENTRY");

return dtList.AsEnumerable().Select(i => new GateEntryModels()
{
GEID = int.Parse(i["GE_ID"].ToString()),
GE_NO = i["GE_NO"].ToString(),
TRANSPORTER = i["TRANSPORTER"].ToString()
}).ToList();
}


I'm trying to wrap multiple list results into a single models and bind the model in to view. When I tried to assign the list value into
oListGateEntryModels
property, its throwing an error. How do I fix this?

Error:


Cannot implicitly convert type '
System.Collections.Generic.List<TS.Models.GateEntryModels>
' to '
TS.Models.DataResult<TS.Models.GateEntryModels>
'

Answer

You're trying to "convert" a list to a type that contains a list, which is not directly possible.

The easiest solution would be to assign the property instead:

oGateEntryViewModel.oListGateEntryModels.ViewResults = oIGateEntryBC.oGetGateEntryData(); 

or

oGateEntryViewModel.oListGateEntryModels = new DataResult<GateEntryModels>
    {
        ViewResults = oIGateEntryBC.oGetGateEntryData()
    };

if you need to initialize the oListGateEntryModels property first.

Comments