.net6中使用ef dbfirst和codefirst(sqlserver、webapi)-爱代码爱编程
Entity Framework(EF):微软官方提供的ORM工具,ORM让开发人员节省数据库访问的代码时间,将更多的时间放到业务逻辑层代码上。EF提供变更跟踪、唯一性约束、惰性加载、查询事物等。开发人员使用Linq语言,对数据库操作如同操作Object对象一样省事。
EF有三种使用场景,1. 从数据库生成Class,2.由实体类生成数据库表结构,3. 通过数据库可视化设计器设计数据库,同时生成实体类。对应三种编程方式:
1.DataBase First:在设计器中逆向生成Model,并有Model自动生成所有的类。
2.Model First:在设计器中创建Model,并用Model生成数据库。所有的类由Model自动生成。
3.Code First:代码优先。
1.DbFirst介绍
1.Nuget包
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.SqlServer.Design
- Microsoft.EntityFrameworkCore.Tools
2.打开程序管理器控制台->默认项目(选择解决方案)
Scaffold-DbContext "Data Source =[数据库地址,本机用.];Initial Catalog =[数据库名称];Persist Security Info=True;User ID=[数据库用户名];Password=[数据库密码];Encrypt=False;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -ContextDir Models -Context CustomerDbContext -Force
3.配置数据库链接字符串
生成CustomerDbContext.cs修改
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
配置文件appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Data Source =[数据库地址,本机用.];Initial Catalog =[数据库名称];Persist Security Info=True;User ID=[数据库用户名];Password=[数据库密码];Encrypt=False;"
把CustomerDbContext对象注入IOC容器进行管理Program.cs
builder.Services.AddDbContext<CustomerDbContext>(option =>
{
option.UseSqlServer("name=ConnectionStrings:DefaultConnection");
});
2.Code Frist介绍
1.Nuget包
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
2.添加数据库表类文件和操作文件
public class User
{
public int ID { get; set; }
public string Account { get; set; }
public string Password { get; set; }
}
public class CustomerDbContext:DbContext
{
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Production> Productions { get; set; }
public CustomerDbContext(DbContextOptions options):base(options)
{
}
}
3.配置数据库连连接字符串
配置文件appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Data Source =[数据库地址,本机用.];Initial Catalog =[数据库名称];Persist Security Info=True;User ID=[数据库用户名];Password=[数据库密码];Encrypt=False;"
把DbContext对象放到IOC容器进行管理Program.cs
builder.Services.AddDbContext<CustomerDbContext>(option =>
{
option.UseSqlServer("name=ConnectionStrings:DefaultConnection");
});
4.打开程序管理器控制台->默认项目(选择解决方案)
初始化:add-migration init
更新:update-database
注:修改表也是当前命令