NetCore + Mysql CodeFirst 生成数据库

守給你的承諾、 提交于 2020-02-09 05:29:01

首先定义领域的模型类,然后配置下面的一些东西,最后执行类

1. 新建Context 继承自 DbContext 

public class EFProjectContext : DbContext
    {
        public EFProjectContext(DbContextOptions<EFProjectContext> options) : base(options)
        {

        } 
        public DbSet<Address> Addreses { get; set; }
        public DbSet<Customer> Customers { get; set; } 
    }

 2.在Startup类中获取mysql 连接字符串

  

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            #region 获取数据库连接字符串 
            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            //var builder = new ConfigurationBuilder();
            //builder.SetBasePath(Directory.GetCurrentDirectory());
            //builder.AddJsonFile("appsettings.json");
            //var connectionStringConfig = builder.Build();
            //var connectionString = connectionStringConfig["ConnectionStrings:DefaultConnection"];
            services.AddDbContext<EFProjectContext>(options => options.UseMySQL(connectionString));
            #endregion

            #region IOC

            services.AddTransient<IRepository<Customer>, Repository<Customer>>();
            services.AddTransient<ICustomerService, CustomerService>();
            #endregion
            #region AutoMapper


            #endregion
        }

  

  3. 在appsettings.json中配置 连接字符串

   

"ConnectionStrings": {
    "DefaultConnection": "Server=localhost;database=netcore_test;uid=root;pwd=root;SslMode=None"
  }

 执行命令:  Add-Migration InitialCreate

       update-database 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!