ASP.Net Core5.0 EF Core使用记录
打算把之前开源的 基于ASP.Net Core开发一套通用后台框架 重新用ASP.Net Core 5写一遍,也算是巩固一下旧知识,学习下新知识。本文是项目搭建初期关于 EF Core 的使用记录
1、项目结构

2、添加引用
LY.Admin.Model项目添加Microsoft.EntityFrameworkCore的NuGet引用,因为我们如果 实体属性 需要使用数据批注方式而不是使用Fluent API的话是需要用到的。
LY.Admin.Repositories项目添加Microsoft.EntityFrameworkCore、Microsoft.EntityFrameworkCore.Design、Microsoft.EntityFrameworkCore.Tools、Pomelo.EntityFrameworkCore.MySql的NuGet引用以及LY.Admin.Model的项目引用。
LY.Admin.Web项目添加Microsoft.EntityFrameworkCore.Design、Pomelo.EntityFrameworkCore.MySql的NuGet引用以及LY.Admin.Repositories的项目引用。
3、创建Model
实体属性有
数据批注和Fluent API两种,我们这里两种混合使用,实际项目中只需要一种就可以了。
Entity
我们所有表基本都是有通用字段的,那么把这些通用字段放到一个父类中更好处理。
public class Entity
{
/// <summary>
/// Id
/// </summary>
[Key]
[Column("id")]
[Comment("主键Id")]
public int Id { get; set; }
/// <summary>
/// 删除标识
/// </summary>
[Column("delete_flag")]
[Comment("删除标识")]
public int DeleteFlag { get; set; }
/// <summary>
/// 创建人
/// </summary>
[Column("created_by")]
[Comment("创建人")]
public int CreatedBy { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[Column("created_time")]
[Comment("创建时间")]
public DateTime CreatedTime { get; set; }
/// <summary>
/// 更新人
/// </summary>
[Column("update_by")]
[Comment("更新人")]
public int? UpdatedBy { get; set; }
/// <summary>
/// 更新时间
/// </summary>
[Column("update_time")]
[Comment("更新时间")]
public DateTime? UpdatedTime { get; set; }
}
4、Post(演示表)
Author字段我们使用Fluent API
[Table("tb_post")]
public class Post : Entity
{
/// <summary>
/// 标题
/// </summary>
[Column("title")]
[Comment("标题")]
public string Title { get; set; }
/// <summary>
/// 内容
/// </summary>
[Column("body")]
[Comment("内容")]
public string Body { get; set; }
/// <summary>
/// 作者 这里使用 Fluent API 方式去控制 具体见 LY.Admin.Repositories.Database.EntityConfigurations.PostConfiguration
/// </summary>
public string Author { get; set; }
}
5、创建DbContext
如果使用
Fluent API是需要在OnModelCreating进行设置的代码如下
DbContext
public class LYAdminDbContext:DbContext
{
/// <summary>
/// 构造函数 调用父类构造函数
/// </summary>
/// <param name="options"></param>
public LYAdminDbContext(DbContextOptions<LYAdminDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
#region 实体属性
// 参考 https://docs.microsoft.com/zh-cn/ef/core/modeling/entity-properties
// 可以使用 数据批注 或者 Fluent API
modelBuilder.ApplyConfiguration(new PostConfiguration());
#endregion
}
public DbSet<Post> Posts { get; set; }
}
PostConfiguration
这里是每个实体类都单独写的,更多API查看实体属性
/// <summary>
/// 实体属性
/// 参考 https://docs.microsoft.com/zh-cn/ef/core/modeling/entity-properties
/// 可以使用 数据批注 或者 Fluent API
/// </summary>
public class PostConfiguration : IEntityTypeConfiguration<Post>
{
public void Configure(EntityTypeBuilder<Post> builder)
{
builder.Property(x => x.Author).HasMaxLength(50).HasColumnType("varchar(50)").HasColumnName("author").HasComment("作者");
}
}
6、LY.Admin.Web
修改Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<LYAdminDbContext>(options =>
{
var connectionString = this.Configuration["ConnectionStrings:MySqlConn"];
//这里现在需要指定版本,暂时设置为自动检测
options.UseMySql(connectionString,ServerVersion.AutoDetect(connectionString));
});
}
appsettings.json配置连接字符串
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MySqlConn": "Server=127.0.0.1;Port=3306;Database=lyadmin;Uid=root;Pwd=123456;charset=utf8;Allow User Variables=True"
}
}
7、数据迁移
打开工具->NuGet包管理器->程序包管理器控制台,默认项目选择LY.Admin.Repositories。输入命令Add-Migration Init。
不出意外可以看到上述项目下自动生成了Migrations文件夹和代码。

如果此时我们觉得又有新的修改,可以直接删除当前迁移文件Remove-Migration。
修改完成后重新添加,然后执行Update-DataBase,就可以在数据库中看到结果了。

注意:__EFMigrationsHistory是记录我们迁移记录的,所以Migrations文件夹和代码不可以手动删除!
后续如果有新的修改,那我们直接Add-Migration XXX(说明),比如Add-Migration AddComment,然后同样执行Update-DataBase就可以了。
笔记
如果想把所有的迁移文件全都删除,重新操作。应该怎么做呢?
首先执行命令:Update-Database -Migration:0
然后执行命令:Remove-Migration,等所有的迁移文件都删除后,重新Add-Migration 、Update-DataBase就可以了。
初始化数据
因为我们使用Code Firsst的方式,是需要在程序一开始运行的时候初始化数据库的,那么,如何初始化?将在后续文章中说明,是需要修改Program.cs文件的,然后加上日志处理。等写完日志处理的时候再补充。
ASP.Net Core5.0 EF Core使用记录的更多相关文章
- ABP CORE 框架入门视频教程《电话薄》基于 Asp.NET Core2.0 EF Core
ABP框架简介 ABP是"ASP.NET Boilerplate Project (ASP.NET样板项目)"的简称. ASP.NET Boilerplate是一个用最佳实践和流行 ...
- ASP.NET core1.0 EF MYSQL搭建中碰到几个问题记录
1.No executable found matching command "dotnet-ef" 看了网上各种办法都没用,最后选择"个人用户账户"创建项 ...
- ASP.NET MVC4.0+EF+LINQ+bui+bootstrap+网站+角色权限管理系统(1)
本系列的的角色权限管理主要采用Dotnet MVC4工程内置的权限管理模块Simplemembership实现,主要有关文件是InitializeSimpleMembershipAttribute.c ...
- ASP.NET MVC4.0+EF+LINQ+bui+网站+角色权限管理系统(7)
今天将使用Simplemembership进行权限控制 我们使用mvc的AuthorizeAttribute来实现对Controller and Action权限控制 看如下标为红色的代码片段: // ...
- ASP.NET MVC4.0+EF+LINQ+bui+网站+角色权限管理系统(6)
快过年了,公司事情忙,好几天没有继续写博客,今天开始写账户模块系统登录,账户管理以及登录日志, 首先新建登录日志数据表: USE [MVCSystem] GO /****** Object: Tabl ...
- ASP.NET MVC4.0+EF+LINQ+bui+网站+角色权限管理系统(5)
我参考了bui官网,里面提供了大量的接口案例和效果,之前下载的前端框架完全不需要bootstrap,所以从这一节开始,不再使用bootstrap(当然不想改变的也可以继续使用之前的框架,不影响使用), ...
- ASP.NET MVC4.0+EF+LINQ+bui+bootstrap+网站+角色权限管理系统(4)
接下来就是菜单管理了,菜单分为两部分,一部分是菜单管理,另一部分是左边的树形菜单 数据库添加菜单表Menus USE [MVCSystem] GO /****** Object: Table [dbo ...
- ASP.NET MVC4.0+EF+LINQ+bui+bootstrap+网站+角色权限管理系统(3)
接下来完成用户.角色的增删查改,以及用户角色.权限的设置 对用户表.角色表做了一些扩展如下[可以更加自己需要增减字段] 相应的M_UserProfile.cs.M_Roles.cs进行扩展 using ...
- ASP.NET MVC4.0+EF+LINQ+bui+bootstrap+网站+角色权限管理系统(2)
创建公共分页参数类Common/GridPager.cs using System; using System.Collections.Generic; using System.Linq; usin ...
随机推荐
- Ionic5手写签名SignaturePad
测试程序下载:https://hanzhe.lanzous.com/itt47kncw3a 初始化项目 1. 首先新建一个Ionic5的项目: ionic start test-1 blank 2. ...
- 1090 Highest Price in Supply Chain
A supply chain is a network of retailers(零售商), distributors(经销商), and suppliers(供应商)-- everyone invo ...
- 754. Reach a Number
You are standing at position 0 on an infinite number line. There is a goal at position target. On ea ...
- php自定义配置文件简单写法
1 <?php 2 header("Content-type:text/html;charset=utf-8"); 3 4 $q = getconfig('rr'); 5 e ...
- 浅谈程序设计和C语言
学前必备知识 程序:一组计算机能识别和执行的指令. 计算机语言:计算机工作基于二进制,计算机只能识别和接受由0和1组成的指令. 计算机能直接识别和接受的二进制代码称为机器指令.机器指令的集合就是该计算 ...
- hdu5253最小生成树
题意:(中文题,直接粘过来吧) 连接的管道 ...
- CVE-2012-0774:Adobe Reader TrueType 字体整数溢出漏洞调试分析
0x01 TrueType 字体 TTF 字体是 Apple 和 Microsoft 两家公司共同推出的字体格式,现在已经广泛的运用于 Windows 操作系统,其中 PDF 文档也可以嵌入 TTF ...
- json对象的获取
<script type="text/javascript"> var person = { //json对象定义开始 name:'tom', //字符串 age:24 ...
- layui处理表单/按钮进行多次提交
在一个项目中,我们最频繁的操作是CRUD,所以一定有涉及到按钮的操作.比如:确认保存,确认编辑,确认删除等等.所以,为了避免表单进行多次提交就显得特别地重要. 代码实现 知识点 $(':button' ...
- 【前端】使用layui、layer父子frame传值
前提: 半前后台分离,前后台都是使用JSON格式的数据进行交互.[化外音,这里我说半分离,是因为使用了themleaf模板进行路由.] 业务说明: 前端通用的逻辑是:列表展示数据,点击事件弹出fram ...