如何在 UWP 中使用预填充的 sqlite 数据库?

How to use pre-populated sqlite database in UWP?

这是我第一次尝试使用 Visual Studio 2015 制作跨平台应用程序。借助网上教程的帮助,我能够在 UWP (Xamarin Forms) 中使用 SQLite。但是,我不知道如何复制预填充的 sqlite 数据库并使用它?

我的代码示例是 -

using Medical_Study.UWP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Xamarin.Forms;

[assembly: Dependency(typeof(SqliteService))]

namespace Medical_Study.UWP
{

    public class SqliteService : ISQLite
    {
        public SqliteService()
        {
        }
        #region ISQLite implementation
        public SQLite.SQLiteConnection GetConnection()
        {
            var sqliteFilename = "QBank.db";
            string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
            var conn = new SQLite.SQLiteConnection(path);

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

要部署预填充的 SQLite DB "QBank.db",您可以将其编译为应用程序的嵌入式资源,并首先 运行 将其复制到 LocalFolder 以供进一步使用。

为此,请将 "QBank.db" 和 select Build Action -> Embedded Resource 添加到您的项目中。

GetConnection()方法可以这样实现:

public SQLite.SQLiteConnection GetConnection()
{
  var sqliteFilename = "QBank.db";

  var assembly = GetType().GetTypeInfo().Assembly;
  var qbankDbResource 
    = assembly.GetManifestResourceNames().FirstOrDefault(name => name.EndsWith(sqliteFilename));
  if (qbankDbResource == null)
  {
    Debug.Assert(false, string.Format("{0} database is not included as embedded resource", sqliteFilename));
    return null;
  }

  string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
  using (var qbankDbStream = assembly.GetManifestResourceStream(qbankDbResource))
  using (var fStream = new FileStream(path, FileMode.Create, FileAccess.Write))
  {
    qbankDbStream.CopyTo(fStream);
  }

  var conn = new SQLite.SQLiteConnection(path);
  // Return the database connection 
  return conn;
}