Jorge Moreira
Jorge Moreira

Reputation: 95

Can't use System.Data.SqlClient on Xamarin.Forms

I need to use System.Data.SqlClient on an app I'm developing with Xamarin.Forms but I'm not able to use this package. I tried adding it to the ".Droid" project (it seems it is not available on PCL) but it's not found in the namespace. I added it through the NuGet Package Manager in Visual Studio 2015.

I need to do something like in here. I know it's not recommended. I plan to develop a REST API later on, but for now I need to do this way in order to build a prototype/alpha version of the app.

EDIT: If I can't use SqlClient, what can I use in Xamarin to open a connection with a SQL Server?

Upvotes: 1

Views: 7134

Answers (3)

Saleem Kalro
Saleem Kalro

Reputation: 1142

Download system.data.sqlite package from NuGet in your app. It will provides you assemblies like system.data, system.data.sqlclient and system.data.sqlLite and much more for database connections.

Upvotes: 0

Brandon Minnick
Brandon Minnick

Reputation: 15400

SQLite is the recommended way for implementing a SQL Database to a Xamarin.Forms app.

Here is a walkthrough to add SQLite to your Xamarin.Forms application!

Walkthrough

1. Add SQLite NuGet Package

Add the SQLite-net NuGet created by @Frank Krueger into each Project in your Solution; i.e. add this NuGet package to your Xamarin.Forms PCL, Android project, etc.

2. Create Database Class

Add this class to your Xamarin.Forms PCL.

This Database class will be used to save data to, and load data from your SQLite Database.

public class Database
{
    #region Constant Fields
    readonly static object _locker = new object();
    readonly SQLiteConnection _database;
    #endregion

    #region Constructors
    public Database()
    {
        _database = DependencyService.Get<ISQLite>().GetConnection();
        _database.CreateTable<DataModel>();
    }
    #endregion

    #region Methods
    public async Task<IList<DataModel>> GetAllDataAsync()
    {
        return await Task.Run(() =>
        {
            lock (_locker)
            {
                return _database.Table<DataModel>().ToList();
            }
        });
    }

    public async Task<int> SaveDataAsync(DataModel dataModel)
    {
        var isDataInDatabase = (await GetAllDataAsync()).FirstOrDefault(x => x.Equals(dataModel)) != null;

        return await Task.Run(() =>
        {
            if (isDataInDatabase)
            {
                lock (_locker)
                {
                    _database.Update(dataModel);
                }
                return dataModel.ID;
            }

            lock (_locker)
            {
                return _database.Insert(dataModel);
            }
        });
    }
    #endregion

3. Create ISQLite Interface

Add this interface to your Xamarin.Forms PCL.

This interface will allow you to use the Dependancy Service to retrieve the database connection using the platform-specific API

public interface ISQLite
{
    SQLiteConnection GetConnection();
}

4. Create iOS Implementation of ISQLite

Add this class to your Android PCL

This Implementation of the ISQLite database will retrieve the database connection using the Xamarin.Android Folder Path.

[assembly: Dependency(typeof(SQLite_Android))]
namespace SampleApp.Droid
{
    public class SQLite_Android : ISQLite
    {
        #region ISQLite implementation
        public SQLiteConnection GetConnection()
        {
            var sqliteFilename = "SQLiteDatabase.db3";
            string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
            var path = Path.Combine(documentsPath, sqliteFilename);

            var conn = new SQLiteConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);

            // Return the database connection 
            return conn;
        }
        #endregion
    }
}

5. In App.cs, Add a Static Implementation to the Database

Add this static implementation of Database.cs into the App class of your Xamarin.Forms PCL.

public class App : Application
{
    static OpportunityModelDatabase _database;

    ...

    public static OpportunityModelDatabase Database =>
        _database ?? (_database = new OpportunityModelDatabase());
}

6. Now Access the Database Data from Anywhere in Your App

Here is an example of how to retrieve the data from a different class

var AllData = await App.Database.GetAllDataAsync();

Sample App

Here is a sample app I've created that demonstrates how to implement SQLite in a Xamarin.Forms app. Feel free to download it to get a better understanding of how to implement SQLite! https://github.com/brminnick/InvestmentDataSampleApp

Upvotes: -1

Demitrian
Demitrian

Reputation: 3230

If you want to use System.Data.SqlClient you will be required to use the approach as mentioned in the post you linked to yourself. The simple reason being that the package is not built as a PCL.

If that's not viable, the use the SQLite.NET package which is PCL compatible.

Upvotes: 2

Related Questions