1.添加并加入
在project.json中添加
"tools": { "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final" }, "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0" }, "Pomelo.EntityFrameworkCore.MySql": "1.0.1", "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final" },
在 tools中加入
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
在dependencies中加入
"Pomelo.EntityFrameworkCore.MySql": "1.0.1", "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
在Startup.cs中加入
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddDbContext<这里填写你的DbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnectionString"))); services.AddMvc(); }
下面这个地方可以直接填写你的数据库连接字符串。//比如 "Server=localhost;database=MySqlDemo;uid=root;pwd=123456;"
services.AddDbContext<这里填写你的DbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnectionString")));
这里的Configuration读取的是appsettings.json 。
所以你要在appsetting.json 添加一个
"ConnectionStrings": { "DefaultConnectionString": "Server=localhost;database=MySqlDemo;uid=Quan;pwd=123456;" },
然后他就可以读到这个字符串了。
当然你的DbContext一定要有构造方法。
public class MySqlDemoContext : DbContext { public MySqlDemoContext(DbContextOptions<MySqlDemoContext> options): base(options) { }
}
这样你的mysql数据库就能练得上了,可以当然但是这样连接上去并存入数据有可能会报错,因为efcore,并不会主动地创建数据库
public class MySqlDemoInitializer { public static void Seed(IApplicationBuilder app) { // Get an instance of the DbContext from the DI container using (var context = app.ApplicationServices.GetRequiredService<MySqlDemoContext>()) { //如果数据库不存在就会去创建 context.Database.EnsureCreated(); //这里半段有无数据在在表里,如果有不初始化数据,如果没有就初始化 if (context.Set<Account>().Any() == false) { SetBasicData(context); SetTestAdmin(context); #if DEBUG SetTestNews(context); SetTestCase(context); SetTestPartner(context); SetTestCompany(context); SetTestPosition(context); SetTestProblem(context); SetTestRefund(context); #endif } } }
这里就是一个初始化的方法,在startup.cs中运行该方法 这个方式初始化有一个不灵活的地方,当程序运行之后只会执行一次。并不会像ef6那样,运行之后也会判断数据库,不存在也会去创建。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //将该方法放于最后执行 MySqlDemoInitializer.Seed(app); }
还有一点,取数据的时候,取出来的Model是不会带有外键
这里就要用贪心加载 这样他就能取出Model所关联的外键
db.Set<Account>() .Include(m => m.Role) .Include(m => m.AccountInfo) .Include(m => m.AccountModules);
还有如何在Controller中使用
public class AccountController : Controller { private AccountService _accountServ; public AccountController(MySqlDemoContext _db) { _accountServ = new AccountService(_db); } }
通过依赖注入,程序会自动将MySqlDemoContext new出来,并注入进来