EntityFrameworkCore 根据实体类自动创建数据库

1.首先新建 Asp.Net Core WebApi 项目

2.添加一下引用 :

2.1   Pomelo.EntityFrameworkCore.MySql(我用的Mysql 根据自己情况引用就行)

2.2  Microsoft.EntityFrameworkCore

2.3 Microsoft.EntityFrameworkCore.Design

3.使项目支持dotnet ef 工具以使用Migrations

3.1 手动修改csproj文件(手动添加是因为在nuget添加Microsoft.EntityFrameworkCore.Tools.DotNet 时报错,估计是vs的问题),添加一下配置

<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>

4.打开CMD命令 cd到项目目录下(C:\Users\Administrator\source\repos\CodeFirst\CodeFirst),执行 

dotnet build

Microsoft (R) Build Engine version 15.1.545.13942 Copyright (C) Microsoft Corporation. All rights reserved. Startup.cs(45,13): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the ‘await‘ operator to the result of the call. [C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo.csproj] EntityFrameworkCoreMigrationsDemo -> C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo\bin\Debug\netcoreapp1.0\EntityFrameworkCoreMigrationsDemo.dll Build succeeded. Startup.cs(45,13): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the ‘await‘ operator to the result of the call. [C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo.csproj] 1 Warning(s) 0 Error(s) Time Elapsed 00:00:04.76

5. 第4步完成后继续执行

 dotnet ef 

可以看见独角兽就说明引用成功了。距离胜利更近一步了

6.创建实例 StudentDbContext和相关实体类

using CodeFirst.Model.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodeFirst.Model.Db
{
  public class StudentDbContext: DbContext
    {
        public StudentDbContext(DbContextOptions<StudentDbContext> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySql(
                @"Server=localhost;Port=3306;Database=Policy;UId=root;Pwd=mysql.com");
        }

        public DbSet<Student> Student { get; set; }
        public DbSet<Teacher> Teacher { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace CodeFirst.Model.Entity
{
   public class Student
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public Teacher Teach { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace CodeFirst.Model.Entity
{
   public class Teacher
    {
        public int Id { get; set; }
        public int Age { get; set; }
        public List<Student> Stus { get; set; }
    }
}

7. 在Startup将StudentDbContext 注册为服务

8.使用Migrations  新建数据库初始化类DbInitializer

using CodeFirst.Model.Db;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace CodeFirst.Model
{
   public class DbInitializer
    {
        public void InitializeAsync(StudentDbContext context)
        {
            //var migrations = await context.Database.GetPendingMigrationsAsync();//获取未应用的Migrations,不必要,MigrateAsync方法会自动处理
             context.Database.MigrateAsync();//根据Migrations修改/创建数据库
        }
    }
}

9.在Startup.cs的Configure方法中,添加参数StudentContext context,netcore会使用DI将DbContext注入到Configure方法,并添加对DbInitializer的调用。

10.使用dotnet ef命令创建Migrations:dotnet ef migrations add text  text随便起名

C:\Users\Administrator\source\repos\CodeFirst\CodeFirst>dotnet ef migrations add Initial

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:02.32
Done. To undo this action, use ‘ef migrations remove‘

如果执行dotnet ef migrations add Initial报错 :

解决办法执行下面两句

PM> dotnet ef Migrations add Init No project was found. Change the current working directory or use the --project option.

定位到csproject

完了继续操作就行

PM> add-migration test

PM> update-database

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

执行成功后,可以看到项目目录下多了个文件夹Migrations,里面就是自动生成的Migrations文件。

创建更新Migrations的命令跟创建初始的一样,只是最后一个参数自己定义即可。

最后执行代码,成功创建了新的数据库,并且里面有一个表__EFMigrationsHistory,是自动生成的用来记录Migrations记录。

修改Student类   public string NewField { get; set; },在命令行执行命令dotnet ef migrations add NewField,然后运行程序,可以看到数据库已经更新,__EFMigrationsHistory表也多了一条对应的记录

生成数据库表:

Demo源码: Github

参考:https://www.cnblogs.com/yhnbgfd/p/6489278.html

原文地址:https://www.cnblogs.com/bin521/p/11697013.html

时间: 2024-08-29 05:06:28

EntityFrameworkCore 根据实体类自动创建数据库的相关文章

学习MVC之租房网站(三)-编写实体类并创建数据库

在上一篇<学习MVC之租房网站(二)-框架搭建及准备工作>中,搭建好了项目框架,并配置了EF.Log4Net和进程外Session.接下来会编写Eneity类并采用CodeFirst的方式创建数据库. 一.数据库表结构举例 1. 在按照CodeFirst方式编写Entity类之前,仍然是需要先搞清楚数据库的表结构.首先肯定会有用户.管理员.角色.权限等相关的表,然后针对租房的特殊场景,还有房屋.房屋家电配置.房子所在的地址包括城市和区域等. 2. 这里面有两张表比较特殊,T_Settings和

打造android ORM框架opendroid(二)——自动创建数据库

在上一篇博客<打造android ORM框架opendroid(一)--ORM框架的使用>中相信你已经了解了opendroid的使用,那么从这篇博客开始,我们正式进入opendroid的源码分析,打造一款自己的ORM框架! 在正式开始之前,你需要保证手里有一份opendroid的源码,如果还没下载opendroid,请到http://git.oschina.net/qibin/OpenDroid 下载opendroid的源码. 任何数据库操作都是从创建数据库开始的,今天我们就来看看opendr

sql2008 计划自动创建数据库分区【转】

本文转自:http://jingyan.baidu.com/article/6b97984d9a26ec1ca3b0bf77.html sql2008 计划自动创建数据库分区 固定增量的数据,自动创建分区作业. 步骤一:创建分区的计划任务 打开MsSQL2008,找到作业该项,如果打不开或者SQL Server代理是未启动状态,请先在windows服务中启动SQL Server代理(参考图片),   右击MsSQL2008对象资源管理器中的作业,选择新建作业,输入该作业你想用的名称,类别不用管,

Hibernate/JPA 自动创建数据库(MySQL)

平时使用Hibernate/JPA映射MySQL时,经常使用到自动创建数据表操作,自动创建MySQL数据库比较少见. 实际上也可以同时创建数据库,修改一下连接配置即可. 常见的配置如下(以Spring Boot中配置方式为例): spring.datasource.url=jdbc:mysql://localhost:3306/dbname?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false

C++数据库实体类自动生成代码模块总结

M系统的关于位置管理服务,一直想抽出来做一个独立健壮的模块. 但C++下没有合适的数据库实体类,或者响应的代码生成工具. 找到一个生成C#的工具,照着生成出来的代码,国庆前写了一个entity代码生成类,主要功能是查询mysql information_schema表下的数据表结构,去生成增删查改的功能,实体类还附带加入了数据缓存. 其实这个homemake数据库实体类,就是DB+MemCache,真实的数据放在DB里,被提前申请的数据用内存来保存. 外部可以根据需要,查询真实数据,或者是内存缓

EF CodeFirst 如何通过配置自动创建数据库&lt;当模型改变时&gt;

最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精    本篇为进阶篇,也是弥补自己之前没搞明白的地方,惭愧惭愧. 如有不明白,请参考:EF CodeFirst 创建数据库 及 EF CodeFirst增删改查之'CRUD' 话不多说,直接上代码: using System; using System.Collections.Generic; using System.Linq; using System

.NET使用DAO.NET实体类模型操作数据库

一.新建项目 打开vs2017,新建一个项目,命名为orm1 二.新建数据库 打开 SqlServer数据库,新建数据库 orm1,并新建表 student . 三.新建 ADO.NET 实体数据模型 这里点击 新建连接,新建数据库连接.其实服务器名输入 . 代表本地服务器,身份验证选择默认的Windows身份认证. 选择我们的创建好的数据库 orm1 . 记住这里的连接名 orm1Entities ,后面写代码需要用到. 这里记得勾选表 点击完成就OK了,有可能会弹出下面的警告,点确定就好了.

【技术】JavaSE环境下JPA实体类自动注册

在没有容器支持的环境下,JPA的实体类(Entity)一般要在persistence.xml中逐个注册,类似下面这样: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w

关于mysql下hibernate实体类字段与数据库关键字冲突的问题

好久没写了,都忘记博客了,趁着现在还在公司,写的东西是经过验证的,不是在家凭记忆力写的,正确率有保障,就说说最近遇到的一件事情吧. 以前一直用的oracle数据库,这次项目我负责的模块所在的系统是用的mysql数据库,结果当初建表时候,字段什么的全靠百度,实在是英语不行,然后有个字段叫usage,是mysql数据库的关键字,当时自己测试时候就发现了,但是想着我只是sql语句,加下``,一样可以用,所以就没引起重视. 结果一期已经上线了,现在对这个表要进行其他的维护,才发现用hibernate直接