UWP: uses Entity Framework Core in UWP to operate SQLite databases.
It is quite common to use the SQLite database to store data in applications. SQLite is used on the UWP Platform. SQLite for Universal Windows Platform and SQLite PCL are generally used. The former is the SQLite engine library, while the latter provides APIs for database operations, however, since Windows Fall Creators Update, we have made a new choice.
Because UWP adds a pair in its Windows Fall Creators Update SDK. NET Standard 2.0, and Entity Framework Core 2.0 (hereinafter referred to as EF Core) also supports. NET Standard 2.0, which enables us to use EF Core in UWP applications to operate SQLite databases. Compared with the former, the most obvious advantage of using EF Core is that Entity Framework features (such as Fluent API and Migration) can be used. In addition, EF Core is implemented. NET Standard and continues iteration, these aspects can be the reason for using EF Core.
Next, we will use a simple example to see how to use EF Core in UWP. Before you start, your environment must meet the following conditions:
- Windows 10 Fall Creators Update (10.0.16299.0 );
- Install the. NET Core 2.0 SDK (or later );
- Visual Studio 2017 is 15.4 or later;
Implementation 1. Create a project
Create a UWP project named LSNote, which is an application that can manage notes. Note: The minimum version should be Windows Fall Creators Update, as shown below:
Then, add a. NET Standard project named LSNote. Model in the solution. We will add some models in this project. Add a reference to the. NET Standard project for the UWP project. The final project structure is as follows:
Note: If the Migration function of EF Core is not used, you do not need to create the following. NET Standard project (we will mention the Migration later). In addition, you can also put the Model in a project separately to make it and other implementations. NET Standard project sharing, such as ASP.net Core or WPF/WinForm (the target framework should be. NET Framework 4.6.1 or higher ).
2. Model project code and Configuration
First, add a reference to EF Core and add a reference to the following two packages through NuGet:
Install-Package Microsoft.EntityFrameworkCore.SqliteInstall-Package Microsoft.EntityFrameworkCore.Tools
The first is the EF Core database itself, and the second provides tools for Migration.
Here is a brief description of Migration (Migration). It incrementally modifies the database and table structure so that the EF Core model is consistent with the database, and does not affect the existing data in the database.
Next, add the following code in the LSNote. Model Project, which includes three classes:
Using Microsoft. entityFrameworkCore; namespace LSNote. model {public class Note {public int Id {get; set;} public string Title {get; set;} public string Content {get; set;} public Category {get; set ;}} public class Category {public int Id {get; set ;}public string Name {get; set ;}} public class NoteDbContext: dbContext {public DbSet <Category> Categories {get; set ;}/// <summary> // path of the database file /// </summary> public string DbFilePath {get; set;} public DbSet <Note> Notes {get; set;} protected override void ongrouping (DbContextOptionsBuilder optionsBuilder) {base. onConfiguring (optionsBuilder); // sets the path of the database file optionsBuilder. useSqlite ($ "Data Source = {DbFilePath}");} protected override void OnModelCreating (ModelBuilder modelBuilder) {base. onModelCreating (modelBuilder); // modelBuilder is required. entity <Category> (). property (m => m. name ). isRequired (); modelBuilder. entity <Note> (). property (m => m. title ). isRequired ();}}}
Where:
- Note: indicates a Note;
- Category: indicates a Category, that is, the Category of the notes;
- NoteDbContext: this class is inherited from DbContext, which includes several DbSet <T> attributes, representing the corresponding data table;
In addition, in NoteDbContext, the meanings of the two methods we reload are as follows:
- OnConfiguring: configures the database. It is executed whenever the DbContext instance is created;
- OnModelCreating: configure the Model and its attributes, and ultimately affect the data table and fields;
Then, to use Migration, we also need to edit the properties of the LSNote. Model Project (edit LSNote. Model. csproj ):
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netcoreapp2.0;netstandard2.0</TargetFrameworks> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> </PropertyGroup> <ItemGroup> <PackageReference Include="microsoft.entityframeworkcore.sqlite" Version="2.0.1" /> <PackageReference Include="microsoft.entityframeworkcore.tools" Version="2.0.1" /> </ItemGroup></Project>
Note that the bold Section is added. The target framework of the current project is. netcoreapp2.0 and. netstandard2.0, And the GenerateRuntimeConfigurationFiles node is added.
In this case, set LSNote. Model to the startup project, and then in the PMC (Package Manager Console), make sure that the Defalut project is also LSNote. Model. Then, run the following command:
Add-Migration Init
Init is the name of the current Migration. Then, we can see that a Migrations folder is generated in the project, which contains class files representing each Migration. They inherit from the Migration class, as shown below:
Note:To run the Migration command, you must set the LSNote. Model project as the startup item, because the current version of EF Core Tools does not support projects of the UWP type.
3. Use it in the UWP Project
First, add a reference to EF Core for the UWP project and run the following command:
Install-Package Microsoft.EntityFrameworkCore.Sqlite
Next, add the following code (BOLD) to the App. xaml. cs file ):
using Microsoft.EntityFrameworkCore; public App() { this.InitializeComponent(); this.Suspending += OnSuspending; DbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "notes.db"); try { using (var con = new LSNote.Model.NoteDbContext()) { con.DbFilePath = DbPath; con.Database.Migrate(); } } catch (NotSupportedException ex) { } catch (Exception ex) { } } public static string DbPath { get; set; }
Use the Migrate method of the DatabaseFacade class to apply the suspended Migration to the Database. If the Database has not been created, it will first create a Database. The DatabaseFacade class is obtained by the con. Database attribute.
Then, in MainPage. xaml. cs, add the following code:
Public sealed partial class MainPage: Page, INotifyPropertyChanged {private List <Note> _ allNotes; public MainPage () {this. initializeComponent (); this. loaded + = MainPage_Loaded;} public event PropertyChangedEventHandler PropertyChanged; public List <Note> AllNotes {get {return _ allNotes;} set {_ allNotes = value; PropertyChanged ?. Invoke (this, new PropertyChangedEventArgs (nameof (AllNotes);} private void MainPage_Loaded (object sender, Windows. UI. xaml. routedEventArgs e) {using (var con = new NoteDbContext () {// set the database path con. dbFilePath = App. dbPath; // Add a category if (con. categories. toList (). count = 0) {var cate1 = new Category {Name = "Category A"}; var cate2 = new Category {Name = "Category B"}; con. categories. addRange (cate1, cate2); con. saveChanges ();} // Add note con. notes. add (new Note {Title = "this is a record", Content = "some remarks", Category = con. categories. first ()}); con. saveChanges (); // query AllNotes = con. notes. toList ();}}}
Add the following code to MainPage. xaml:
<Page ... xmlns:model="using:LSNote.Model" ... <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <ListView x:Name="list" ItemsSource="{x:Bind AllNotes, Mode=OneWay}"> <ListView.ItemTemplate> <DataTemplate x:DataType="model:Note"> <StackPanel Margin="0,4"> <TextBlock FontSize="16" FontWeight="SemiBold" Text="{x:Bind Title}" /> <TextBlock Text="{x:Bind Content}" /> <TextBlock> <Run Text="Category:" /> <Run Text="{x:Bind Category.Name}" /> </TextBlock> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid></Page>
In this case, set the UWP project to a startup project and press F5 to run the project. The result is displayed:
4. Further use of Migration
As mentioned above, we can use EF Core to use its own features. For example, when we want to modify the existing database or table structure, it will be very easy to use Migration. For the preceding Note object, we need to Add a new IsDelete attribute for it, and then use the Add-Migration command and the Migrate method to ultimately influence the database.
First, add attributes:
public bool IsDelete { get; set; }
Next, you still need to set LSNote. Model as the startup project, and confirm in PMC that the Defalut project is also the same, enter the command:
Add-Migration AddIsDeleteField
In this case, the corresponding class file will be generated in the Migrations folder.
Switch the startup project to a UWP project, and add the following code (bold part) in MainPage. xaml ):
<DataTemplate x:DataType="model:Note"> <StackPanel Margin="0,4"> <TextBlock FontSize="16" FontWeight="SemiBold" Text="{x:Bind Title}" /> <TextBlock Text="{x:Bind Content}" /> <TextBlock> <Run Text="Category:" /> <Run Text="{x:Bind Category.Name}" /> </TextBlock> <TextBlock> <Run Text="IsDelete:" /> <Run Text="{x:Bind IsDelete}" /> </TextBlock> </StackPanel> </DataTemplate>
Press F5 to view the updated result:
Additional Words: Migration
- For SQLite, the Migration of EF Core still has some restrictions and cannot meet all functions, such as adding Foreign keys and primary keys after creating a data table. There is a complete list of restricted operations. If these operations are included in Migration, NotSupportedException will be triggered. However, it is worth noting that, with the continuous improvement of EF Core, these restrictions should be implemented one by one in the future;
- In addition, we recommend that youBack up data;
Summary
This article mainly discusses how to use EF Core in UWP because both of them depend on and support it. NET Standard 2.0, so EF Core can be used in UWP and run on any device that supports Win 10. Next, if the application you are developing or preparing for development will use the SQLite database, try EF Core.
References:
Getting Started with EF Core on Universal Windows Platform
The Secret to Running EF Core 2.0 Migrations from a NET Core or NET Standard Class Library
Source code download