EntityFramwork Core环境搭建

1.步骤:创建实体类-->创建DbContext-->生成数据库-->编写调用EF CORE代码
2.引用NuGet包:Install-Package Microsoft.EntityFrameworkCore.SqlServer
3.创建实现了IEntityTypeConfiguration接口的实体配置类,配置实体类和数据库表的对应关系,其中主键、字段长度、表名也可在实体类中使用Arribute进行标注[key]、[table]....**--------
a.步骤:创建实体类-->创建DbContext-->生成数据库-->编写调用EF CORE代码
b.引用NuGet包:Install-Package Microsoft.EntityFrameworkCore.SqlServer
c.创建实现了IEntityTypeConfiguration接口的实体配置类,配置实体类和数据库表的对应关系【Fluent API】,其中主键、字段长度、表名也可在实体类中使用Arribute[DATA Annotations]进行标注[key]、[table]、[Required]、 但是推荐使用Fluent API
....

  public class apilogConfig : IEntityTypeConfiguration<tbase_apilog>
    {
        public void Configure(EntityTypeBuilder<tbase_apilog> builder)
        {
            builder.ToTable("tbase_apilog");
            builder.Property(x => x.client_ip).HasMaxLength(200);
            builder.Property(x => x.request_header).HasDefaultValue("");

        }
    }

4.创建数据库上下文

public class MyDbContext : DbContext
    {
      public DbSet<tinf_billio_finish>  tinf_Billio_Finishes { get; set; }
       //所有的实体类都要加进来

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer("连接字符串");
        }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
        }

    }

4.EF 迁移脚本
--安装EFCORE 迁移工具包:Microsoft.EntityFrameworkCore.Tools
--生成迁移脚本 add-migration name
--更新到数据库 update-database name(或者不选会执行最新的迁移脚本)
--删除迁移脚本 remove-migration (删除最后一次迁移脚本)
--生成sql脚本 script-migration (name选填)
--生成sql脚本 A-B script-migration a~b (生成两次迁移记录之间的脚本)
5.反向工程
根据数据库表生成实体类
scaffold-dbcontext '连接字符串' Microsoft.EntityFrameworkCore.SqlServer
使用反向工程生成的实体类可能不能满足项目要求 可能要手动 修改或者增加配置
再次运行反向工程工具 对文件做的修改可能会丢失
6.分层项目中 入口程序引用 Microsoft.EntityFrameworkCore.Design Microsoft.EntityFrameworkCore.SqlServer 类库项目引用 Microsoft.EntityFrameworkCore.Relational Microsoft.EntityFrameworkCore.SqlServer
入口项目中配置连接信息:
`builder.Services.AddDbContext(opt =>
{
string constr = builder.Configuration.GetSection("ConnectionStrings:constr").Value;
opt.UseSqlServer(constr);
});`
类库项目中DbContext 格式:
` public class MyDbContext : DbContext
{
//将参数信息传给父类
public MyDbContext(DbContextOptions options):base(options)
{

    }
    public DbSet<Books>  Books { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);//从当前程序集获取配置

    }
}`
posted @ 2022-07-05 10:19  Wilson_it  阅读(152)  评论(0编辑  收藏  举报