c# - 在 Windows Phone 8.1 类库中创建 SQLite 数据库

标签 c# database sqlite windows-phone-8.1 portable-class-library

我有一个 Windows Phone 8.1 类库,稍后我想添加它作为对 Windows Phone 8.1 应用程序项目的引用。

这个类库应该负责创建和管理它自己的数据库。我尝试在我的 ClassLibrary 中创建一个新的 SQLiteConnection,但它抛出以下错误: A first chance exception of type 'System.InvalidOperationException' occurred in SQLitePCL.DLL 然而,如果我在我的 MainApp 中做同样的事情一切正常。

那么,是否可以在没有 MainApp 的任何支持的情况下,在负责创建和管理它的 ClassLibrary 中创建一个 SQLite 数据库。

最佳答案

我有一个项目,其中 SQLite 库位于一个类库中,然后我使用另一个类库来实现我的应用程序和 SQLite 库之间的通信

类库:SQLite.Library

  1. 创建一个新的类库(在我的例子中,我将其命名为 SQLite.Library)
  2. 右键单击 > 管理 NuGet 包 > sqlite-net ( https://www.nuget.org/packages/sqlite-net/1.0.8 )

添加此 NuGet 包后,您会看到您的类库有 2 个新类:SQLite.cs 和 SQLiteAsync.cs。

还有一个已知的 SQLite 和线程问题(NullReferenceException when page Loads),您可以通过在 SQLite.cs 中的 TableMapping GetMapping 方法中添加锁来修复它:

public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None)
{
    if (_mappings == null) {
        _mappings = new Dictionary<string, TableMapping> ();
    }

    lock (_mappings)
    {
        TableMapping map;
        if (!_mappings.TryGetValue(type.FullName, out map))
        {
            map = new TableMapping(type, createFlags);
            _mappings[type.FullName] = map;
        }
        return map;
    }   
}

类库:Solutionname.Lib

  1. 制作一个新的类库(在我的例子中,我将其命名为 Solutionname.Lib)
  2. 右键 > 添加引用 > 解决方案 > SQLite.Library(你刚刚创建的类库)

设置引用后,您可以使用该类库中的SQLite库。

在我的项目中,我试图拆分我的代码,所以我开始创建一个名为 DatabaseHelper.cs 的类:

public class DatabaseHelper
    {
        private String DB_NAME = "DATABASENAME.db";

        public SQLiteAsyncConnection Conn { get; set; }

       public DatabaseHelper()
        {
            Conn = new SQLiteAsyncConnection(DB_NAME);
            this.InitDb();

        }

        public async void InitDb()
        {
            // Create Db if not exist
            bool dbExist = await CheckDbAsync();
            if (!dbExist)
            {
                await CreateDatabaseAsync();
            }
        }

        public async Task<bool> CheckDbAsync()
        {
            bool dbExist = true;

            try
            {
                StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync(DB_NAME);
            }
            catch (Exception)
            {
                dbExist = false;
            }

            return dbExist;
        }

        private async Task CreateDatabaseAsync()
        {
            //add tables here
            //example: await Conn.CreateTableAsync<DbComment>();
        }
    }

创建 DatabaseHelper 类后,您可以开始为数据库中的每个表创建一个数据源类。 在我的例子中,我有一个 CommentDataSource.cs:

  public class CommentDataSource
{
    private DatabaseHelper db;

    public CommentDataSource(DatabaseHelper databaseHelper)
    {
        this.db = databaseHelper;
    }

    public async Task<long> AddComment(String vat, String comment)
    {
        long id = 0;
        DateTime date = DateTime.Now;
        DbComment dbc = new DbComment(vat, comment, date);
        await db.Conn.InsertAsync(dbc);

        DbComment insertDbc = await db.Conn.Table<DbComment>().ElementAtAsync(await db.Conn.Table<DbComment>().CountAsync() - 1);
        if (insertDbc != null)
        {
            id = insertDbc.Id;
        }

        return id;
    }

    public async void RemoveComment(long idComment)
    {
        DbComment comment = await db.Conn.Table<DbComment>().Where(c => c.Id == idComment).FirstOrDefaultAsync();
        if (comment != null)
        {
            await db.Conn.DeleteAsync(comment);
        }
    }

    public async Task<List<DbComment>> FetchAllComments(String vat)
    {
        return await db.Conn.Table<DbComment>().Where(x => x.VAT == vat).ToListAsync();
    }
}

如您所见,您将添加的所有数据源都将使用相同的数据库助手。

在您的应用中使用 Solutionname.Lib

  1. 右键 > 添加引用 > 解决方案 > SQLite.Library(你刚刚创建的类库)
  2. 右键单击 > 添加引用 > 解决方案 > Solutionname.Lib

你仍然需要添加对你的 sqlite 库的引用,否则你会得到错误。

现在你可以开始使用你的数据源类了,就像你在这里看到的:

private DatabaseHelper db = new DatabaseHelper();
private CommentDataSource commentDataSource;

 public MainPage()
        {
            this.InitializeComponent();
            commentDataSource = new CommentDataSource(db);
        }

现在 CommentsDataSource 的每个方法都可以在您的应用中使用。

希望对您有所帮助!

关于c# - 在 Windows Phone 8.1 类库中创建 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25788639/

相关文章:

sqlite - 在 SQLite 中,如何进行 Join 避免列中的特定重复

sqlite - SQLite 中的 URL 编码

c# - 是否可以在 Web API 服务中托管两个不同的 Odata 模型

c# - ASP.NET 成员更改密码不起作用

c# - 导出数据到excel mobile

php - 存储 JSON 响应的最佳方式?

ruby-on-rails - rails : how to eager load limited records of ordered association without N+1 queries

java - Java 中的 DriverManager.getConnection 使用相对路径

C# 字典到 json - 自动排序

sqlite - 如何删除错误 "Cant find PInvoke DLL SQLite.interop.dll"