一、新建项目
二、安装必须的nuget包

三、新建几个实体模型
1.我建了一 DAL文件夹,新建上下文FonourDBContext.cs
using Microsoft.EntityFrameworkCore;
namespace Domain
{
public class FonourDBContext: DbContext
{
public FonourDBContext(DbContextOptions<FonourDBContext> options)
: base(options)
{
}
public DbSet<Department> Departments { get; set; }
public DbSet<Menu> Menus { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } } }
2.建立几个Departments等的实体
3.Startup.cs 修改 ConfigureServices(IServiceCollection services) 方法,增加对EF的支持(黄色高亮):
// This method gets called by the runtime. Use this method to add services to the container.
2 public void ConfigureServices(IServiceCollection services)
3 {
4 // Add framework services.
5 services.AddApplicationInsightsTelemetry(Configuration);
6
7 services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")));
8
9 services.AddMvc();
10
11 }
4.上面的 SqlServerConnection 是我们的数据库连接字符串,它的配置在 \src\appsettings.json 文件中(这个名字让我们想起了appsetting.config):
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SqlServerConnection": "Server=.;Data Source=(local);uid=sa;pwd=js123456;DataBase=myDataBase;"
}
}
三。在控制台使用
使用CodeFirst数据库迁移命令创建数据库
Add-Migration Init
Update-Database
