26

EFCore使用(1) - 添加创建数据库

 3 years ago
source link: http://blog.devwiki.net/index.php/2020/05/24/efcore-create-database.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1. 创建 EFCoreApp项目

使用 VS2019 新建 net core App 空项目, 其项目配置如下:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>
</Project>

ERR3IjY.png!web

2. 安装 EF Core

打开 VS 的 工具 -> NuGet 包管理器, 使用界面或者命令行安装 EF Core

ERzYBjB.png!web

在搜索栏 搜索 ef core , 选择 ef core 安装:

7nUf6nU.png!web

接收安装许可:

Q3YjYnY.png!web

接下来安装 sqlite, 选择 ef core.sqlite 进行安装并接受许可.

查看项目文件可看到已经安装了两个包:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.4" />
  </ItemGroup>

</Project>

3. 使用EF Core

EF Core中一个很重要的类是 : DbContext , 我们需要继承此类 编写数据库操作的代码.

namespace EFCoreApp.Data
{
    public class AppDbContext : DbContext
    {
        public DbSet<KeyValueTable> KeyValues { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlite("Data Source=App.db");
        }
    }

    [Table("KeyValue")]
    public class KeyValueTable
    {
        [Key]
        public string Id{ get; set; }
        [Column("key")]
        public string Key { get; set; }
        [Column("value")]
        public string Value { get; set; }
    }
}

这里我们继承了 DbContext 并连接数据库 App.db , 创建一个数据表: KeyValue .

然后需要在 App 启动回调中 创建数据库:

namespace EFCoreApp
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            AppDbContext dbContext = new AppDbContext();
            dbContext.Database.EnsureCreated();
        }

        private void App_OnExit(object sender, ExitEventArgs e)
        {
        }
    }
}

启动 运行后我们可以看到 创建的 数据库文件: App.db , 打开数据库可以看到创建的数据表.

emmeyeV.png!web

至此, EF Core 的安装使用第一部分到此结束. 下一部分看看 如何进行 数据库的常用操作: 增 改 删 查

4 项目地址

本项目代码地址在此: DevWiki/EFCoreApp


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK