1

I created a simple local database by using SQLite.net - PCL, and inserted some data in it. My question is what is the easiest way to get one of the objects, or all of the obejects stored in the database?

My database:

namespace DatabaseDemo
{
    public class Database
    {
        readonly SQLiteAsyncConnection _database;

        public Database(string path)
        {
            _database = new SQLiteAsyncConnection(path);
            _database.CreateTableAsync<Model>().Wait();
        }

        public Task<int> SaveItemAsync(Model person)
        {
            if (person.ID != 0)
            {
                return _database.UpdateAsync(person);

            }
            else
            {
                return _database.InsertAsync(person);
            }
        }
    }
}

My Model class:

namespace DatabaseDemo
{
    public class Model
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Name { get; set; }
    }
}
Joey Zhang
  • 363
  • 6
  • 18
  • this is fairly well documented - https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/databases/ – Jason Mar 27 '17 at 05:15
  • The tutorial is using a Listview to display all data, but I just want to print some data on Application output. That's why I post here – Joey Zhang Mar 27 '17 at 05:20
  • 1
    you asked about accessing a local db, which is the same regardless of whether or not you are using a ListView or writing to the console. Just because a tutorial doesn't do the exact same thing that you need doesn't mean that you can't learn from it. – Jason Mar 27 '17 at 05:23
  • You can use a generic repository http://stackoverflow.com/a/29856945/1970317 – EvZ Mar 27 '17 at 17:33

1 Answers1

3

to retrieve the data from SQLite Database you can use the below methods.

Retrieve All:

public IEnumerable<Model> GetModels()  
{  
    return (from t in _database.Table<Model>() select t).ToList();  
}

And to retrieve select id:

public Model GetModel(int id)  
{  
    return _sqlconnection.Table<Model>().FirstOrDefault(t => t.Id == id);  
}

Hope this is what you are looking for. or let me know if I misunderstood.

Thank You.

Chandresh Khambhayata
  • 1,748
  • 2
  • 31
  • 60