I am using xamarin forms and Sqlite-net-pcl (nuget). I need help on creating multiple tables. I have set up the requirements as below. I need to do the following:
1) I need to create tables and database when the App launches. How to do this in App.cs?
Update Problem:
1) Tables are not created. Why?
---1--- in PCL : add these
-- classes for table
using SQLite;
namespace MyApp.Model
{
[Table("TblCountry")]
public class Country
{
public string Country { get; set; }
public string CountryCode { get; set; }
public string OfficialLanguage { get; set; }
}
[Table("TblEmployees")]
public class Employee
{
[PrimaryKey, AutoIncrement]
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
}
}
--- interface class
using System;
using System.Collections.Generic;
using System.Text;
using SQLite;
namespace MyApp.DataAccessHelpers
{
public interface ISQLite
{
SQLiteConnection GetConnection();
}
}
---2---in Xamarin.Droid: I add this class
using SQLite;
using System.IO;
using Xamarin.Forms;
using MyApp.Droid.Implementation;
using MyApp.DataAccessHelpers;
[assembly: Xamarin.Forms.Dependency(typeof(AndroidSQLite))]
namespace MyApp.Droid.Implementation
{
class AndroidSQLite : ISQLite
{
public SQLite.SQLiteConnection GetConnection()
{
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
var path = Path.Combine(documentsPath, DatabaseHelper.DbFileName);
var conn = new SQLite.SQLiteConnection(path);
return conn;
}
}
}
------- Update :
public class DatabaseHelper
{
static SQLiteConnection sqliteconnection;
public const string DbFileName = "MyDb.db3";
public DatabaseHelper()
{
try
{
sqliteconnection = DependencyService.Get<ISQLite>().GetConnection();
sqliteconnection.CreateTable<CountryModel>();
sqliteconnection.CreateTable<EmployeeModel>();
}
catch (Exception ex)
{
string strErr = ex.ToString();
}
}
public List<CountryModel> GetAllCountry()
{
return (from data in sqliteconnection.Table<CountryModel>()
select data).ToList();
}
public CountryModel GetCountryByHuNbr(string name)
{
return sqliteconnection.Table<CountryModel>().FirstOrDefault(c => c.Name == name);
}
public void DeleteAllCountry()
{
sqliteconnection.DeleteAll<CountryModel>();
}
public void DeleteCountryByid(int ID)
{
sqliteconnection.Delete<CountryModel>(ID);
}
public void InsertCountry(CountryModel country)
{
sqliteconnection.Insert(country);
}
public void UpdateCountry(CountryModel country)
{
sqliteconnection.Update(country);
}
//------- CRUD for employee
public void InsertEmployee(EmployeeModel employee)
{
sqliteconnection.Insert(employee);
}
.....
... and all the CRUD for employee
}
}
Thanks in advance.