zoukankan      html  css  js  c++  java
  • [UWP小白日记-11]在UWP中使用Entity Framework Core(Entity Framework 7)操作SQLite数据库(一)

    前言

      本文中,您将创建一个通用应用程序(UWP),使用Entity Framework Core(Entity Framework 7)框架在SQLite数据库上执行基本的数据访问。

    准备:

      Entity Framework Core(Entity Framework 7)下文将简称:EF

      1.在UWP中使用EF需要更新Microsoft.NETCore.UniversalWindowsPlatform到大于“5.2.2”的版本。

      2.直接在“程序包管理器控制台”输入命令来更新:Update-Package Microsoft.NETCore.UniversalWindowsPlatform 

      

      如果没有的话下图打开:建议保留在上图的位置

      

      安装EF:

      1.同样使用命令来安装:Install-Package Microsoft.EntityFrameworkCore.Sqlite

      2.应为我们以后维护数据也得用EF,所以还要安装工具包:Install-Package Microsoft.EntityFrameworkCore.Tools –Pre

    创建数据模版

      在项目上添加一个或多个Class文件,这些Class类就是最后生成的数据库表。

    1.数据表代码

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Dome.UWP.Models
    {
        /// <summary>
        /// 设置数据表
        /// </summary>
        [Table(name: "AccountBook")]
        class AccountBook
        {
            /// <summary>
            /// 设置编号列:不能为空、主键
            /// </summary>
            [Required,Key]
            public int 编号 { get; set; }
            public decimal 金额 { get; set; }
            public DateTime 日期 { get; set; }
            public string 备注 { get; set; }
            public string 收支类型 { get; set; }
            public string 标签名称 { get; set; }
            public string 标签图标 { get; set; }
            public string 标签备注 { get; set; }
            public string 账户名称 { get; set; }
        }
    }

    2.说明

      代码中的[Table(name:"AccountBook")]指定数据表的名称,如果不指定的话会默认使用你定义的数据上下文中的属性命名表了(下文会提到),这里是演示下。

      中文字段?不用在意这些细节。

      还有编号public int 编号 { get; set; }上的[Required,Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)],前面2个在代码中有说明主要说下最后一个:

    它的意思是就是“自增”的意思。

      到这数据模型就创建完成了。

    创建数据上下文

    1.数据上下文代码 

    using jizhang.UWP.Models;
    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Data.Common;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Dome.UWP.Services
    {
        class EFdbContext:DbContext
        {
            
            public DbSet<AccountBook> books { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                //配置数据库名
                optionsBuilder.UseSqlite("FileName=jizhang.db");
            }
        }
    }

    2.说明

      这个代码很少,主要说下:public DbSet<AccountBook> books { get; set; }如果你在数据模型中没有指定表名的话就会使用这个名字来命名数据表。

    还有就是你创建了多少个表就应该在这声明多少个这个格式属性,如果你不声明的话最后在数据库中不会出现没有声明的数据表了。

    创建数据库

       Warning:本文现在为止在UWP项目中使用EF Tools还是不能正常工作的。需要手动添加binding redirects(绑定重定向).

      1.在项目中添加一个文本文件。命名为App.config

      2.向文件中添加如下类容:

    <configuration>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.IO.FileSystem.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="4.0.0.0" newVersion="4.0.1.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Threading.Overlapped" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="4.0.0.0" newVersion="4.0.1.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="4.1.0.0" newVersion="4.0.0.0"/>
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
    </configuration>

      3.好了现在有了一个数据模型,你就可以使用migrations 来生成数据库文件了。

    会在你的项目中自动添加一个migrations 文件夹

        1)使用命令来生成:Add-Migration MyFirstMigration

    MyFirstMigration你可以随意写,就是个名字罢了。(在这一步前最好编译一次项目,减少出错的几率。

          这一步命令在哪输入?小白都是懵逼的,就在上文用来安装EF框架的那个“程序包控制台”里输入就行了

        2)如果你的数据模型改变了那么你得重新执行这个命令来更新数据库。

      4.由于我们是在APP运行的设备上使用数据库,所以得在运行设备上创建数据库。不用担心会多次创建数据库只会在第一次运行的时候创建。

    那我们要怎么把创建的MyFirstMigration转到数据库中呢?

      5.你会发现编译过后还是没有数据库文件<数据的位置>(%USERPROFILE%AppDataLocalPackages

        1)你会发现打开是这样的,简直是泪奔不可能每次找APP的东西都去打开清单文件复制包名。

       

        2)所以建议在项目创建的时候改掉包名,并且把这个Packages文件夹创建快捷方式放桌面。

      

      6.最后我们打开APP.xaml.cs文件在构造函数中添加下面的代码。

    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 EFdbContext()) { db.Database.Migrate(); } } }

       1.好了我们的数据库就创建好了。

    总结

      差点忘了说了,如果你不执行Add-Migration MyFirstMigration命令,其他的工作你都做了那么最后也会生成数据库文件但是只有一个__EFMigrationsHistory表

    下一篇我再说具体操作数据。

  • 相关阅读:
    《Java程序设计》终极不改版【下】
    《Java程序设计》终极不改版【下】
    !终端伪装测试之fuck校园网
    !终端伪装测试之fuck校园网
    关于js中单双引号以及转义符的理解
    关于js中单双引号以及转义符的理解
    关于js中单双引号以及转义符的理解
    正则表达式【第二卷】
    正则表达式【第二卷】
    正则表达式【第二卷】
  • 原文地址:https://www.cnblogs.com/Enious/p/5893615.html
Copyright © 2011-2022 走看看