1,需要用到的dll
Microsoft.EntityFrameworkCore;
Pomelo.EntityFrameworkCore.MySql.
1,建立数据库test,并建立表person,并新建id、name、content三个字段。
2,配置数据库链接appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MySQL": "server=127.0.0.1;userid=root;password=123456;database=test;"
}
}
3,建立model :Person.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetCore.Core
{
public class Person
{
public string Id { set; get; }
public string Name { set; get; }
public string Content { set; get; }
}
}
4,自定义dbcontext
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetCore.Core.Base
{
public class MysqlDbContext:DbContext
{
//注意属性名必须和表名一致,否则会报错找不到表
public DbSet<Person> Person { get; set; }
public MysqlDbContext(DbContextOptions<MysqlDbContext> options) : base(options)
{
}
}
}
5,配置容器注入,Startup.cs,在ConfigureServices方法加入代码
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MysqlDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MySQL"), MySqlServerVersion.LatestSupportedServerVersion));services.AddDbContext<MysqlDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MySQL"), MySqlServerVersion.LatestSupportedServerVersion));
services.AddRazorPages();
services.AddControllers();
services.AddMvc();
}
6,测试,不需要实例化,如图示例,容器会在调用的时候自动实例化
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using NetCore.Core.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetCore.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly MysqlDbContext _mySqlDBContext;
public IndexModel(ILogger<IndexModel> logger, MysqlDbContext mySqlDBContext)
{
_logger = logger;
_mySqlDBContext = mySqlDBContext;
}
public void OnGet()
{
var item= _mySqlDBContext.Person.FirstOrDefault(c => c.Id == "123");
if (item != null)
{
_mySqlDBContext.Person.Remove(item);
_mySqlDBContext.SaveChanges();
}
// _mySqlDBContext.Person.Add(new Core.Person { Id = "123", Name = "xm", Content = "xxx" });
// _mySqlDBContext.SaveChanges();
}
}
}