【UWP】基于EntityFrameWorkCore的新数据库配置过程 (Updated 2020.01.14)

前言

之前UWP课程中曾经配置了一下EFCORE数据库,当时爬这个坑爬了将近能有三天,现在整理一下配置顺序,原来用来记录的txt文件是用英文记录的,这边稍微整理一下吧。

Notes :
  • Updated 2020.01.14
    • 现在微软的EntityFrameWork3.0并不支持UWP新数据库的使用,该博客内容更新为 —— 如何降低版本( 使用 EntityFrameWorkCore 2.2 )搭建UWP数据库
    • 开发环境适配要求 : VisualStudio版本大于2015 (本人在VS2019中进行了搭建,亲测可行)
    • 文档所维护的版本 : EntityFrameWork Core 2.2
  • Updated 2018.07.15
    • 建议配合官方文档食用
    • 开发环境适配要求
      • VisualStudio 2015/2017
      • dotnet core version ≥ 2.0
      • dotnet standard version ≥ 2.0

正文
Part1 : 数据库的创建
  • 创建一个UWP解决方案
  • 在你的项目中创建一个 .net Standard 文件,同时将它作为解决方案中的启动项目set it as the ‘StartUP’ project under the same solution
    • 请注意,除了设置为启动项目外,也需要在nuget管理器界面中,将默认启动项目调整为你的数据库项目!
      例 : (EasyChat.DataBase.net Standard 项目)
      在这里插入图片描述
  • 打开Nuget管理器,在控制台执行(Update 2020.01.14)
    • Install-Package NETStandard.Library -Version 2.0.3
    • Install-Package Microsoft.EntityFrameWorkCore.Sqlite -Version 2.2.0
    • Install-Package Microsoft.EntityFrameWorkCore.tools -Version 2.2.0
  • 右键新创建的EFCORE文件中项目根目录(位置如下图),点击“编辑.csproj文件”
    这里写图片描述
    在其中的<TargetFrameworks> 处,ctrl+c & ctrl+v以下代码(覆盖该对应行)
	<TargetFrameworks>netcoreapp2.0;netstandard2.0</TargetFrameworks> 
	<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
  • net中的数据库与一般的E-R数据库有点类似,数据以类为单位存储,每个类成员(字段)对应的就是我们关系型数据库中的每个表的表项,此处仅以学生-选课-课程模型中的学生表为例:
	//student.class 

	using System;
	using System.ComponentModel.DataAnnotations;
	using Microsoft.EntityFrameworkCore;

	namespace DB
	{
	    public class Student
	    {

	        public int ID { get; set; }
	        public string Number { get; set; }
	        public string Name { get; set; }
	        public int grade { get; set; }
	    }
	    public class StudentContext : DbContext
	    {
	        public DbSet<Student> Students { get; set; }
	        protected override void OnConfiguring(DbContextOptionsBuilder builder)
	        {
	            builder.UseSqlite("Data Source = student.db");
	        }
	    }
	}
  • 打开控制台,在控制台依次执行

    • Add-Migration [MigrationName]
      • PS : [MigrationName] 意为可以随便命名,如 Add-Migration helloworld
  • 重新打开我们刚刚打开的.csproj文件,将刚刚我们修改的<TargetFrameworks> 标签修改为

    <TargetFrameworks>netstandard2.0</TargetFrameworks> 
    
    • 注意 :<GenerateRuntimeConfigurationFiles> 标签对不需要修改
  • 以上,我们完成了数据库的搭建,接下来的部分,我们将开始在UWP数据库中对其进行引用

  • 首先,将UWP程序作为解决方案中的启动项目

  • ( Update 2020.01.14 ) 打开Nuget管理器,将默认项目更改为UWP,在控制台执行: Install-Package Microsoft.EntityFrameWorkCore -Version 2.2.0

  • 在UWP项目中添加对.net项目的引用

  • 添加以下代码于app.xaml.cs(需添加处增加了备注 // Add):

    using Microsoft.EntityFrameworkCore; //Add
    using System;
    using Windows.ApplicationModel;
    using Windows.ApplicationModel.Activation;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;
    
    namespace EFGetStarted.UWP
    {
        /// <summary>
        /// Provides application-specific behavior to supplement the default Application class.
        /// </summary>
        sealed partial class App : Application
        {
            /// <summary>
            /// Initializes the singleton application object.  This is the first line of authored code
            /// executed, and as such is the logical equivalent of main() or WinMain().
            /// </summary>
            public App()
            {
                this.InitializeComponent();
                this.Suspending += OnSuspending;
    
                using (var db = new studentContext()) //Add
                { //Add
                    db.Database.EnsureCreated();// Add
                }// Add
            }
            ...
    

PART2 : 在UWP中进行增删查改
  • 将UWP项目设为启动项目(set it as the ‘start-up’ project)

  • 增删查改样例代码如下 :

    //新增数据
     private async void add_Click(object sender, RoutedEventArgs e)
        {
            using (var db = new studentContext())
            {
                Student s = new Student
                {
                    ID = (int) DateTime.Now.Ticks,
                    Name = name.Text,
                    Number = number.Text,
                    grade = int.Parse(score.Text)
                };
                db.Students.Add(s);
                await db.SaveChangesAsync();
            }
        }
       
    //查询数据
        private async void query_Click(object sender, RoutedEventArgs e)
        {
            using (var db = new studentContext())
            {
                member.Text = (await db.Students.CountAsync()).ToString();
            }
        }
    
    //数据删除
        private void delete_Click(object sender, RoutedEventArgs e)
        {
            using (var db = new studentContext())
            {
                db.Database.Migrate();
            }
        }
      
    
  • 开始你的新数据库使用之旅吧!


技术文档补充 :
References:
  1. MicroSoft官方文档 (Updated 2020.01.04 : 现已变为ASP.NET Core的搭建GuideLines)
  2. Special Thanks to the first user giving feedback under the official document, though the feedbacks under the document is closed now without a reason why 😦
  3. My Teacher, Professor Zhang Yin
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值