简体   繁体   中英

How to create local database for universal app in Visual Studio 2015?

How can I create a local database for universal app in visual studio 2015?

I can't find any solution for it. I found some solutions like SQLite for Windows Phone 8.1 but those solutions can not available in VS2015. Can anyone help me how to create this local database?

I want to create a WP 8.1 application and to have a local database to the phone itself. I don't want any online database like Azure.

You have to install the correct VS extension depending on the project type. For a universal app, the correct extension is named "SQLite for Universal App Platform" and can be download here : https://visualstudiogallery.msdn.microsoft.com/4913e7d5-96c9-4dde-a1a1-69820d615936?SRC=VSIDE . For a WP 8.1 project, the correct extension is SQLite for Windows Phone 8.1.

Next, you have to add a reference in your project (available with the previous extension) : References > Universal Windows > Extensions > SQLite for Universal App Platform.

For simplicity, you need a nuget package : SQLite-Net-PCL (keep case).

In the code, you can create an entity with some attributes :

public class Test
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Value { get; set; }
}

Next, you can open a connection populate and read the database by this way :

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

Note : the api is fully synchrone, so a Task.Run (like in my sample) can be a good practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM