如何在Visual Studio 2015中为通用应用程序创建本地数据库

本文关键字:应用程序 创建 数据库 Visual Studio 2015 | 更新日期: 2023-09-27 18:12:04

如何在visual studio 2015中创建通用应用程序的本地数据库?

我找不到任何解决办法。我找到了一些解决方案,如Windows Phone 8.1的SQLite,但这些解决方案在VS2015中不可用。谁能帮助我如何创建这个本地数据库?

我想创建一个WP 8.1应用程序,并有一个本地数据库到手机本身。我不想要任何像Azure这样的在线数据库

如何在Visual Studio 2015中为通用应用程序创建本地数据库

您必须根据项目类型安装正确的VS扩展。对于一个通用的应用程序,正确的扩展名为"SQLite通用应用程序平台",可以在这里下载:https://visualstudiogallery.msdn.microsoft.com/4913e7d5-96c9-4dde-a1a1-69820d615936?SRC=VSIDE。对于WP 8.1项目,正确的扩展名是SQLite For Windows Phone 8.1。

接下来,你必须在你的项目中添加一个参考(与以前的扩展一起可用):参考资料>通用Windows>扩展> SQLite for Universal App Platform。

为了简单起见,您需要一个nuget包:SQLite-Net-PCL (keep case)。

在代码中,您可以创建一个具有以下属性的实体:
public class Test
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Value { get; set; }
}

接下来,您可以打开一个连接填充并通过以下方式读取数据库:

await Task.Run(() =>
{
    ISQLitePlatform platform = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
    using (SQLiteConnection connection = new SQLiteConnection(platform, Path.Combine(ApplicationData.Current.LocalFolder.Path, "mydb.db")))
    {
        connection.CreateTable<Test>(); // create if not exists
        var test = new Test
        {
            Value = "test"
        };
        connection.Insert(test);
        //var lastInsertedId = platform.SQLiteApi.LastInsertRowid(connection.Handle);
        var lastInsertedId = test.Id; // more simple
        var value = connection.Find<Test>(lastInsertedId);
        Debug.WriteLine(value);
    }
});

注意:api是完全同步的,所以一个任务。