无法将类型'System.Collections.Generic.List隐式转换为C#中的类属性

时间:2016-08-31 21:15:04

标签: c# asp.net-mvc

型号:

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

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

控制器:

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();  
}

我正在尝试将多个列表结果包装到单个模型中,并将模型绑定到视图中。当我尝试将列表值分配到oListGateEntryModels属性时,它会抛出错误。我该如何解决这个问题?

错误:

  

无法将类型“System.Collections.Generic.List<TS.Models.GateEntryModels>”隐式转换为“TS.Models.DataResult<TS.Models.GateEntryModels>

2 个答案:

答案 0 :(得分:1)

您正在尝试将列表“转换”为包含列表的类型,这是不可能的。

最简单的解决方案是分配属性:

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

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

如果您需要首先初始化oListGateEntryModels属性。

答案 1 :(得分:0)

您必须明确进行转换,请尝试转换:

List<GateEntryModels> listName = dtList.AsEnumerable().Select(i => new MyType()
{
   GEID = i.Field<string>("GE_ID"),
   GE_NO = i.Field<string>("GE_NO"),
   TRANSPORTER = i.Field<double>("TRANSPORTER ")
}).ToList();

return listName;