c# - How to read data from database and put it into model -


i'm building application in store provinces , cities of country. have 2 models:

public class province {     public int id { get; set; }     public string name { get; set; } }  public class city {     public int id { get; set; }     public string name { get; set; }     public province province { get; set; } } 

this way read province data database:

public static list<province> readlist() {     var list = new list<province>();      using (var connection = new mysqlconnection(_connectionstring))     {         using (var cmd = new mysqlcommand("select * province;", connection))         {             connection.open();              mysqldatareader reader = cmd.executereader();              while (reader.read())             {                 list.add(new province()                 {                     id = convert.toint32(reader["id"]),                     name = reader["name"].tostring()                 });             }              reader.close();         }     }      return list; } 

and works fine. problem while reading city data:

public static list<city> readlist() {     var list = new list<city>();      using (var connection = new mysqlconnection(_connectionstring))     {         using (var cmd = new mysqlcommand("select * city;", connection))         {             connection.open();              mysqldatareader reader = cmd.executereader();              while (reader.read())             {                 list.add(new province()                 {                     id = convert.toint32(reader["id"]),                     name = reader["name"].tostring(),                     province = ???                 });             }              reader.close();         }     }      return list; } 

i know can provinceid reader["provinceid"] don't know should province data itself? should provinceviewmodel?

since view models in different project, how can that?

i don't know i'm wrong here?

a solution problem is, without making use of orm, following: under

var list = new list<city>(); 

declare list provinces , fill province have - have way read data stated above.

var provinces = getprovinces(); 

the method getprovinces returns list of provinces have.

then in method read each record cities:

list.add(new city() {     id = convert.toint32(reader["id"]),     name = reader["name"].tostring(),     province = provinces.singleordefault(x=>x.id==convert.toint32(reader["provinceid"])); }); 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -