smeacham

ItemDatabaseGenerics.cs

Jun 8th, 2016
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.13 KB | None | 0 0
  1. using SQLite;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Xml.Linq;
  8. using Xamarin.Forms;
  9.  
  10. namespace SQLiteNetPCLVS
  11. {
  12.     public class ItemDatabaseGeneric
  13.     {
  14.         protected static object locker = new object();
  15.         protected SQLiteConnection database;
  16.  
  17.         public ItemDatabaseGeneric()
  18.         {
  19.             database = DependencyService.Get<IDatabase>().DBConnect();
  20.             database.CreateTable<Item>();
  21.             database.CreateTable<Person>();
  22.         }
  23.  
  24.         public IEnumerable<T> GetObjects<T> () where T: IObject, new ()
  25.         {
  26.             lock (locker)
  27.             {
  28.                 return (from i in database.Table<T>() select i).ToList();
  29.             }
  30.         }
  31.  
  32.         public IEnumerable<T> GetFirstObjects<T> () where T: IObject, new ()
  33.         {
  34.             lock (locker)
  35.             {
  36.                 // TODO - fix this so the table in the SELECT is also dynamic
  37.                 return database.Query<T>("SELECT * FROM Item WHERE Name = 'First'");
  38.             }
  39.         }
  40.  
  41.         public T GetObject<T>(int id) where T: IObject, new ()
  42.         {
  43.             lock (locker)
  44.             {
  45.                 return database.Table<T>().FirstOrDefault(x => x.ID == id);
  46.             }
  47.         }
  48.  
  49.         public int SaveObject<T>(T obj) where T : IObject
  50.         {
  51.             lock (locker)
  52.             {
  53.                 if (obj.ID != 0)
  54.                 {
  55.                     database.Update(obj);
  56.                     return obj.ID;
  57.                 } else
  58.                 {
  59.                     return database.Insert(obj);
  60.                 }
  61.             }
  62.         }
  63.  
  64.         public int DeleteObject<T>(int id) where T: IObject, new ()
  65.         {
  66.             lock (locker)
  67.             {
  68.                 return database.Delete<T>(id);
  69.             }
  70.         }
  71.  
  72.         public void DeleteAllObjects<T>() where T: IObject, new()
  73.         {
  74.             lock (locker)
  75.             {
  76.                 database.DropTable<T>();
  77.                 database.CreateTable<T>();
  78.             }
  79.         }
  80.     }
  81. }
Add Comment
Please, Sign In to add comment