David Smith

David Smith

  • 2.1k
  • 21
  • 410

Cannot convert list<model> to model

Dec 17 2021 7:21 PM

Hi,

I am trying to bind a model to an select element in Blazor /.net 5. I already have one that reads a json file and that works fine but this one I am trying to get the data from a database. The problem comes when I try and get the DataTable into my Model.  So I created a List<Model> and am trying to get it into my model. I am getting "cannot convert type list<model> to model" error. I have also tried a foreach item in list, add the item (note commented out section) but that is giving an NullReference error on the  USStates.States even though I have a "new" on the model (StatesModel).

Can anyone tell me how to do this correctly? Help Appreciated..Thanks...

private StatesModel USStates { get; set; }

private Task GetStatesModel()
        {
            DataTable dt = new DataTable();
            SQL.GetSQLData exe = new SQL.GetSQLData();
            dt = (DataTable)exe.GetValues("storedProcName", "ConnStringName");
            
            List<StateModel> StateList = Data.Conversion.ConvertDataTabletoModel.ConvertToList<StateModel>(dt);
            
            USStates = StateList;   --- Cannot Convert list<statemodel> to statemodel

            //foreach (var item in StateList)
            //{
            //    USStates.States.Add(item);   -- Null Reference exception.
            //}           
            
            return Task.CompletedTask;
        }       

and my Model......

 public class StatesModel
    {     
        public List<StateModel> States { get; set; } = new List<StateModel>();        
    }

public class StateModel
    {
        public string StateName { get; set; }
        public string StateAbbreviation { get; set; }
    }

---------------------------------------------------------------------------------------------------

FYI I also tried this   USStates.States = StateList; - and I get a null reference exception at runtime on this line.


Answers (4)