NetCore + Mysql CodeFirst 生成数据库
首先定义领域的模型类,然后配置下面的一些东西,最后执行类
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