【问题标题】:Create a SQLite Database in Windows Phone 8.1 Class Library在 Windows Phone 8.1 类库中创建 SQLite 数据库
【发布时间】:2014-11-05 11:21:07
【问题描述】:

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

这个 ClassLibrary 应该负责创建和管理它自己的数据库。我尝试在我的 ClassLibrary 中创建一个新的SQLiteConnection,但它会引发以下错误:A first chance exception of type 'System.InvalidOperationException' occurred in SQLitePCL.DLL 但是,如果我在 MainApp 中执行相同操作,一切正常。

那么,是否有可能在 ClassLibrary 中创建一个 SQLite 数据库,该数据库负责创建和管理它而无需 MainApp 的任何支持。

【问题讨论】:

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


    【解决方案1】:

    我有一个项目,其中 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 的每个方法。

    希望对你有所帮助!

    【讨论】:

      【解决方案2】:

      试试这个

       public async Task<bool> CheckDbAsync(string dbName)
          {
              bool dbExist = true;
      
              try
              {
                  StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync(dbName);
              }
              catch (Exception)
              {
                  dbExist = false;
              }
      
              return dbExist;
          }
          public async Task CreateDatabaseAsync(string dbName)
          {
              SQLiteAsyncConnection con = new SQLiteAsyncConnection(dbName);
      
              await con.CreateTableAsync<ChatClass>();
             // await con.CreateTableAsync<RecentChatManageClass>();
              await con.CreateTableAsync<PurchasedGift>();
      
              // await con.CreateTableAsync<AttandanceManagement>();
          }   
      

      并像这样使用

       DataBaseOperation databaseoperation = new DataBaseOperation();
                  bool existDb = await databaseoperation.CheckDbAsync("sample.db"); // Check Database created or not 
                  if (!existDb)
                  {
                      await databaseoperation.CreateDatabaseAsync("sample.db"); // Create Database 
                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多