一、新建項目
二、安裝必須的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