创建的Windows Phone 8.1类库SQLite数据库 [英] Create a SQLite Database in Windows Phone 8.1 Class Library

查看:276
本文介绍了创建的Windows Phone 8.1类库SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想在以后添加作为一款Windows Phone 8.1应用程序项目的引用一款Windows Phone 8.1类库。结果



这ClassLibrary应该是负责创建和管理其自己的数据库。我试图创建一个新的 SQLiteConnection 在我的ClassLibrary,但它引发以下错误:的'System.InvalidOperationException'类型的第一个机会异常出现在SQLitePCL .DLL 但是,如果我这样做,我MainApp一切工作正常。
搜索结果
那么,是不是可以创建在ClassLibrary这是负责创建和未经MainApp任何支持其管理SQLite数据库。


< DIV CLASS =h2_lin>解决方案

我在这一个项目中,SQLite库是一个类库,然后我用另外一个类库通讯我的应用程序和SQLite库

类库:SQLite.Library




  1. 请一新的类库(在我的情况下,我把它命名为SQLite.Library)

  2. 右键单击>管理的NuGet包>源码网(的https://www.nuget.org/packages/sqlite-net/1.0.8



补充你看到你的类库有2个新的类此的NuGet包后:SQLite.cs和SQLiteAsync.cs



也有与SQLite和线程(的href=\"http://stackoverflow.com/questions/17538275/nullreferenceexception-when-page-loads\">的NullReferenceException),你可以解决它的已知问题在SQLite.cs方法 TableMapping GetMapping 加把锁:

 公共TableMapping GetMapping(类型类型,createFlags createFlags = CreateFlags.None)
{
如果(_mappings == NULL){
_mappings =新词典<字符串,TableMapping> ();
}

锁(_mappings)
{
TableMapping图;
如果
{
=地图新TableMapping(类型,createFlags)(_mappings.TryGetValue(type.FullName,出图)!);
_mappings [type.FullName] =图;
}
返回地图;
}
}



类库:Solutionname.Lib




  1. 请一个新的类库(在我的情况下,我把它命名为Solutionname.Lib)

  2. 右键点击>添加引用>解决方案> SQLite.Library(类库你刚刚做)



在设置基准后u能使用SQLite库在这个类库。



在项目中,我试图分裂我的代码了一点,所以我开始制作一个名为 DatabaseHelper.cs类

 公共类DatabaseHelper 
{
私有String DB_NAME =DATABASENAME.db;

公共SQLiteAsyncConnection康恩{搞定;组; }

公共DatabaseHelper()
{
=康涅狄格州新SQLiteAsyncConnection(DB_NAME);
this.InitDb();

}

公共异步无效initdb的()
{
//创建分贝,如果不存在
布尔dbExist =等待CheckDbAsync() ;
如果(dbExist!)
{
等待CreateDatabaseAsync();
}
}

公共异步任务<布尔> CheckDbAsync()
{
布尔dbExist = TRUE;


{
StorageFile SF =等待ApplicationData.Current.LocalFolder.GetFileAsync(DB_NAME);
}
赶上(例外)
{
dbExist = FALSE;
}

返回dbExist;
}

私人异步任务CreateDatabaseAsync()
{
//添加表在这里
//例如:等待Conn.CreateTableAsync< DbComment>() ;
}
}



创建DatabaseHelper U类可以通过启动后使每个表数据源类在数据库中。
在我来说,我有一个 CommentDataSource.cs



 公共类CommentDataSource 
{
私人DatabaseHelper分贝;

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

公共异步任务<长> AddComment(增值税字符串,字符串评论)
{
长ID = 0;
日期时间日期= DateTime.Now;
DbComment DBC =新DbComment(增值税,评论,日期);
等待db.Conn.InsertAsync(DBC);

DbComment insertDbc =等待db.Conn.Table< DbComment>()ElementAtAsync(等待db.Conn.Table< DbComment方式>()CountAsync() - 1)。
如果(insertDbc!= NULL)
{
ID = insertDbc.Id;
}

返回ID;
}

公共异步无效RemoveComment(长idComment)
{
DbComment评论=等待db.Conn.Table< DbComment方式>()式(C => ; c.Id == idComment).FirstOrDefaultAsync();
如果(发表评论!= NULL)
{
等待db.Conn.DeleteAsync(注解);
}
}

公共异步任务<名单,LT; DbComment>> FetchAllComments(字符串增值税)
{
返回等待db.Conn.Table< DbComment>()式(X => x.VAT ==增值税).ToListAsync();
}
}



正如你可以看到所有的数据源,美将增加将使用相同的databasehelper



使用的Solutionname.Lib在你的应用




  1. 右键单击>添加引用>解决方案> SQLite.Library(类库你刚刚做)

  2. 右键单击>添加引用>解决方案>解决方案名称。库



您仍需要一个引用添加到您的sqlite的lib,否则你会得到错误。



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

 私人DatabaseHelper DB =新DatabaseHelper(); 
私人CommentDataSource commentDataSource;

公众的MainPage()
{
this.InitializeComponent();
commentDataSource =新CommentDataSource(DB);
}

现在是在您的应用程序提供的CommentsDataSource的每一个方法。



希望这有助于UA位!


I have a Windows Phone 8.1 Class Library that I want to later add as a reference to a Windows Phone 8.1 App project.

This ClassLibrary should be responsible for creating and managing its own database. I tried creating a new SQLiteConnection in my ClassLibrary, but it throws the following error: A first chance exception of type 'System.InvalidOperationException' occurred in SQLitePCL.DLL however, if I do the same in my MainApp everything works fine.

So, is it possible to create a SQLite database in a ClassLibrary that's responsible for creating and managing it without any support from the MainApp.

解决方案

I have a project in it where the SQLite library is in a class library and then I use another class library for the communication between my app and the SQLite library

Class library: SQLite.Library

  1. Make a new class library (in my case I named it SQLite.Library)
  2. Right click > Manage NuGet packages > sqlite-net (https://www.nuget.org/packages/sqlite-net/1.0.8)

After adding this NuGet package you see that your class library has 2 new classes: SQLite.cs and SQLiteAsync.cs.

Also there is a known problem with SQLite and threading (NullReferenceException when page Loads), you can fix it by adding a lock in the method TableMapping GetMapping in SQLite.cs:

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;
    }   
}

Class library: Solutionname.Lib

  1. Make a new class library (in my case I named it Solutionname.Lib)
  2. Right click > Add Reference > Solution > SQLite.Library (the class library u just made)

After the reference is set u can use the SQLite library in this class library.

In my project I tried to split my code a bit so I started with making a class named 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>();
        }
    }

After the creation of the DatabaseHelper class u can start by making a datasource class for each table in your database. In my case i have a 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();
    }
}

As you can see all the datasources that u will add will make use of the same databasehelper.

Use the Solutionname.Lib in your app

  1. Right click > Add Reference > Solution > SQLite.Library (the class library u just made)
  2. Right click > Add Reference > Solution > Solutionname.Lib

You still need to add a reference to your sqlite lib otherwise you will get errors.

Now you can start using your datasource classes, like u can see here:

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

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

Now is every method of the CommentsDataSource available in your app.

Hope this help u a bit!

这篇关于创建的Windows Phone 8.1类库SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆