- 使用Nuget导入所需要的EF 核心包以及对应数据库的驱动包,我用的是sqlserver(.net 支持的所有数据库)
Install-Package Microsoft.EntityFrameworkCore.SqlServer
- 创建model
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
- appsettings加入ConnetionString
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"SqlServer": "Data Source=.;Initial Catalog=WebDemo;User Id=sa;Password=******;"
}
}
- Startup.cs启动文件给 Context 注入ConnetionString
public void ConfigureServices(IServiceCollection services)
{
var connetion = Configuration.GetConnectionString("SqlServer");
services.AddDbContext<WebDemoContext>(options=>options.UseSqlServer(connetion), ServiceLifetime.Singleton,ServiceLifetime.Singleton);
services.AddMvc();
}
- 自定义上下文对象
public class WebDemoContext : DbContext
{
public WebDemoContext(DbContextOptions<WebDemoContext> options):base(options)
{
}
public DbSet<User> User { get; set; }
}
对数据库进行迁移后,接下来就可以使用 WebDemoContext 对 User 进行CRUD了