2013-08-31 20 views
0

新手SQLite中如何轉換的QueryTable到的ObservableCollection

我不設法一個的QueryTable#SQlite的轉換爲C#一個ObservableCollection(WindowsStore)。

我的意思是,我創建了一個名爲person的類,該類繼承自BindableBase。 (模型):

class Person : BindableBase 
{ 
    private int _id; 
    public int id { get { return _id; } set {SetProperty(ref _id, value);} } 

    private string _Name; 
    public string Name { get { return _Name; } set {SetProperty(ref _Name, value);} } 

    private string _LastName; 
    public string LastName { get {return _LastName;} set {SetProperty(ref _LastName, value);} } 

    private double _Celphone; 
    public double Celphone { get {return _Celphone;} set {SetProperty(ref _Celphone, value);} } 

} 

我創建了一個名爲PersonCollection(模型)

class PersonCollection: ObservableCollection<Person> 
{ 
} 

OK,現在,當我嘗試用表的數據(視圖模型),以填補集合,我可以在另一個類不要向ObservableCollection轉換tablequery。如何解決這個問題。

我ViewModel類:

class PersonVM: BindableBase 
{  
    private PersonCollection _PersonList; 
    public PersonCollection PersonList {get {return _PersonList;} 
             set {SetProperty(ref _PersonList, value);} } 



    public async Task<bool> GetPersons() 
    { 
     try 
     { 
      var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.db3"); 
      using (var db = new SQLite.SQLiteConnection(dbPath)) 
      { 
       var listadepersonas = from x in db.Table<Person>() select x; 
       foreach (var persona in listadepersonas) 
       { 
        PersonList.Add(new Person() 
        { id = persona.id, Name = persona.LastName, 
         LastName = persona.LastName, Celphone = persona.Celphone }); 
       } 
       db.Dispose(); 
       db.Close(); 
      } 

      return true; 
     } 
     catch (Exception ex) 
     { 
      string sErr = ex.Message; 
      return false; 
     }       
} 

和異常返回我: ex.Message = 「未將對象引用設置到對象的實例。」

回答

0

您未初始化PersonList,所以PersonList爲空。這就是爲什麼你得到NullReferenceExceptionObject reference not set to an instance of an object.

public async Task<bool> GetPersons() 
{ 
    try 
    { 
     var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.db3"); 

     //Initialize the PersonList, so PersonList won't be null. 
     PersonList = new PersonCollection(); 
     using (var db = new SQLite.SQLiteConnection(dbPath)) 
     { 
      var listadepersonas = from x in db.Table<Person>() select x; 
      foreach (var persona in listadepersonas) 
      { 
       PersonList.Add(new Person() 
       { 
        id = persona.id, 
        Name = persona.LastName, 
        LastName = persona.LastName, 
        Celphone = persona.Celphone 
       }); 
      } 
      db.Dispose(); 
      db.Close(); 
     } 

     return true; 
    } 
    catch (Exception ex) 
    { 
     string sErr = ex.Message; 
     return false; 
    } 
} 
+0

這就是當你不休息和睡眠發生!... thnks! – Makito

相關問題