1、使用Nuget加载sql的EFCore方法"MySql.EntityFrameworkCore"
2、新建一个类文件继承自DbContext如下:
public class DMESCore:DbContext
{
public DMESCore(DbContextOptions<DMESCore> options ):base(options)
{
}
或者是使用 以上只能二选一
public DMESCore()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("server=localhost;port=3306;database=jbdmes;user=root;pwd=123456;charset=utf8;");
}
}
3、查询信息(注意DBSet<>的内容必须是真实的表名称)
using(var db=App.Provider.GetRequiredService<DMESCore>())
{
var res= db.User.Where(e => e.id < 10).ToList();
}
或者使用
using (DMESCore db = new DMESCore())
{
var rd = db.User.Where(e => e.id < 10).ToList();
}
注意:
同样可以采用一下方法进行获取
上述方法的使用前提是:单访问量,不存在多线程操作,不存在同时读写操作,否则就会提示错误:”A second operation started on this context before a previous asynchronous operation completed“,
如果出现多线程操作可采用如下方法:
不在app.xml.cs中注入数据库。
而是每次使用前都NEw一次。这样就可以保证不冲突,
配置如下:
public DMESCore()
{
}
public DMESCore(DbContextOptions<DMESCore> options ):base(options)
{
}
public DbSet<User> User { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("server=localhost;port=3306;database=jbdmes;user=root;pwd=123456;charset=utf8;");
}
如果不使用依赖注入则会出现连接字段暴露出来,则使用ioptions进行封装
注入配置文件改为嵌入资源 较新则复制
var config=new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("AppSetting.json",false,true)
.Build();
var res= config.GetSection("AppSetting").Get<AppSetting>();
_Service.Configure<AppSettings>(builder.GetSection("AppSettings"));
IOptions<AppSettings> //获取配置文件内容