简体   繁体   English

无法在Xamarin.Forms上使用System.Data.SqlClient

[英]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. 我需要在我使用Xamarin.Forms开发的应用程序上使用System.Data.SqlClient ,但无法使用此程序包。 I tried adding it to the ".Droid" project (it seems it is not available on PCL) but it's not found in the namespace. 我尝试将其添加到“ .Droid”项目中(似乎在PCL上不可用),但未在名称空间中找到它。 I added it through the NuGet Package Manager in Visual Studio 2015. 我是通过Visual Studio 2015中的NuGet包管理器添加的。

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. 我计划稍后再开发REST API,但现在我需要这样做,以便构建该应用程序的原型/ alpha版本。

EDIT: If I can't use SqlClient, what can I use in Xamarin to open a connection with a SQL Server? 编辑:如果我不能使用SqlClient,我可以在Xamarin中使用什么来打开与SQL Server的连接?

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. 如果要使用System.Data.SqlClient ,则需要使用链接到自己的文章中提到的方法。 The simple reason being that the package is not built as a PCL. 原因很简单,该软件包不是作为PCL构建的。

If that's not viable, the use the SQLite.NET package which is PCL compatible. 如果这不可行,请使用与PCL兼容的SQLite.NET软件包

Download system.data.sqlite package from NuGet in your app. 从您的应用程序中的NuGet下载system.data.sqlite软件包。 It will provides you assemblies like system.data , system.data.sqlclient and system.data.sqlLite and much more for database connections. 它将为您提供诸如system.datasystem.data.sqlclientsystem.data.sqlLite类的程序集,以及更多用于数据库连接的程序集。

SQLite is the recommended way for implementing a SQL Database to a Xamarin.Forms app. 建议将SQLite实施到Xamarin.Forms应用程序的SQL数据库。

Here is a walkthrough to add SQLite to your Xamarin.Forms application! 这是将SQLite添加到Xamarin.Forms应用程序的演练!

Walkthrough 演练

1. Add SQLite NuGet Package 1.添加SQLite NuGet包

Add the SQLite-net NuGet created by @Frank Krueger into each Project in your Solution; @Frank Krueger创建的SQLite-net NuGet添加到解决方案中的每个项目中; ie add this NuGet package to your Xamarin.Forms PCL, Android project, etc. 即将此NuGet程序包添加到您的Xamarin.Forms PCL,Android项目等中。

2. Create Database Class 2.创建数据库类

Add this class to your Xamarin.Forms PCL. 将此类添加到您的Xamarin.Forms PCL。

This Database class will be used to save data to, and load data from your SQLite Database. 该数据库类将用于将数据保存到SQLite数据库以及从SQLite数据库加载数据。

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 3.创建ISQLite接口

Add this interface to your Xamarin.Forms PCL. 将此接口添加到您的Xamarin.Forms PCL。

This interface will allow you to use the Dependancy Service to retrieve the database connection using the platform-specific API 该界面将允许您使用依赖服务来使用特定于平台的API来检索数据库连接。

public interface ISQLite
{
    SQLiteConnection GetConnection();
}

4. Create iOS Implementation of ISQLite 4.创建ISQLite的iOS实现

Add this class to your Android PCL 将此类添加到您的Android PCL

This Implementation of the ISQLite database will retrieve the database connection using the Xamarin.Android Folder Path. ISQLite数据库的此实现将使用Xamarin.Android文件夹路径检索数据库连接。

[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 5.在App.cs中,向数据库添加静态实现

Add this static implementation of Database.cs into the App class of your Xamarin.Forms PCL. Database.cs此静态实现添加到Xamarin.Forms PCL的App类中。

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 6.现在从您应用程序中的任何位置访问数据库数据

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. 这是我创建的一个示例应用程序,演示了如何在Xamarin.Forms应用程序中实现SQLite。 Feel free to download it to get a better understanding of how to implement SQLite! 随时下载它可以更好地了解如何实现SQLite! https://github.com/brminnick/InvestmentDataSampleApp https://github.com/brminnick/InvestmentDataSampleApp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 只能调试不使用System.Data.SqlClient类部署xamarin应用程序 - can only debug not deploy xamarin app with System.Data.SqlClient class used 似乎无法修复:System.BadImageFormatException:无法加载文件或程序集“System.Data.SqlClient” - Can't seem to fix: System.BadImageFormatException: Could not load file or assembly 'System.Data.SqlClient' EntityFramework 可以使用提供程序 System.Data.SqlClient 的标准连接字符串吗? - Can EntityFramework use a standard connection string of provider System.Data.SqlClient? 无法使用c#System.Data.SqlClient连接到本地数据库 - Can not connect to local database with c# System.Data.SqlClient 当我使用 System.Data.SqlClient 版本 4.4.3 时,无法加载文件或程序集 System.Data.SqlClient,版本 = 4.2.0.2 - Could not load file or assembly System.Data.SqlClient, Version=4.2.0.2 when I use System.Data.SqlClient Version 4.4.3 无法通过System.Data.SqlClient连接 - Cannot connect via System.Data.SqlClient 无法找到 System.Data.SqlClient 引用 - Unable to locate System.Data.SqlClient reference 此平台不支持 System.Data.SqlClient - System.Data.SqlClient is not supported on this platform 无法安装System.Data.SqlClient - Unable to install the System.Data.SqlClient NET标准的System.Data.SqlClient错误 - Error with System.Data.SqlClient with .NET standard
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM