在Windows Phone 8.1类库中创建SQLite数据库 [英] Create a SQLite Database in Windows Phone 8.1 Class Library
问题描述
我有一个Windows Phone 8.1类库,我想稍后添加为对Windows Phone 8.1应用程序项目的引用。
此ClassLibrary应该负责创建和管理自己的数据库。我尝试在我的ClassLibrary中创建一个新的 SQLiteConnection
,但它引发以下错误: SQLitePCL中发生类型'System.InvalidOperationException'的第一次机会异常.DLL
然而,如果我在MainApp中做同样的一切工作正常。
所以,可以在ClassLibrary中创建一个SQLite数据库,负责在没有MainApp的任何支持的情况下创建和管理它。
< divite =h2_lin>解决方案
我有一个项目,其中SQLite库是在一个类库,然后我使用另一个类库的我的应用程序和SQLite库之间的通信
类库:SQLite.Library
- 新类库(在我的例子中我命名为SQLite.Library)
- 右键单击>管理NuGet软件包> sqlite-net( https://www.nuget.org/packages/sqlite-net/1.0.8 )
添加这个NuGet包后,你会看到你的类库有两个新类:SQLite.cs和SQLiteAsync.cs。
此外,SQLite和线程存在一个已知问题(页面加载时的NullReferenceException)你可以通过在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
- 创建一个新的类库(在我的例子中我命名为Solutionname.Lib)
- 右键>添加引用>解决方案> SQLite.Library(类库u刚刚创建)
在这个类库中使用SQLite库。
在我的项目中,我试图拆分我的代码,所以我开始创建一个名为 DatabaseHelper.cs :
public class DatabaseHelper
{
private String DB_NAME =DATABASENAME.db;
public SQLiteAsyncConnection Conn {get;组; }
public DatabaseHelper()
{
Conn = new SQLiteAsyncConnection(DB_NAME);
this.InitDb();
}
public async void InitDb()
{
//如果不存在则创建Db
bool dbExist = await CheckDbAsync ;
if(!dbExist)
{
await CreateDatabaseAsync();
}
}
public async任务< bool> CheckDbAsync()
{
bool dbExist = true;
try
{
StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync(DB_NAME);
}
catch(Exception)
{
dbExist = false;
}
return dbExist;
}
private async任务CreateDatabaseAsync()
{
//在此处添加表
//示例:await Conn.CreateTableAsync< DbComment> ;
}
}
创建DatabaseHelper类后,为数据库中的每个表创建一个datasource类。
在我的case我有一个 CommentDataSource.cs :
public class CommentDataSource
{
private DatabaseHelper db;
public CommentDataSource(DatabaseHelper databaseHelper)
{
this.db = databaseHelper;
}
public async任务< 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>()。其中(c = ; c.Id == idComment).FirstOrDefaultAsync();
if(comment!= null)
{
await db.Conn.DeleteAsync(comment);
}
}
public async任务< List< DbComment>> FetchAllComments(String vat)
{
return await db.Conn.Table< DbComment>()。其中(x => x.VAT == vat).ToListAsync
}
}
正如你可以看到u将添加的所有数据源
在您的应用程序中使用Solutionname.Lib
- 右键>添加引用>解决方案> SQLite.Library(刚刚创建的类库)
- 右键单击>添加引用>解决方案> Lib
您仍然需要添加对sqlite库的引用,否则您会收到错误。
现在你可以开始使用你的数据源类,比如u可以看到:
private DatabaseHelper db = new DatabaseHelper();
private CommentDataSource commentDataSource;
public MainPage()
{
this.InitializeComponent();
commentDataSource = new 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
- Make a new class library (in my case I named it SQLite.Library)
- 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
- Make a new class library (in my case I named it Solutionname.Lib)
- 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
- Right click > Add Reference > Solution > SQLite.Library (the class library u just made)
- 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屋!