1.首先新建一个空白解决方案EFCoreDemo
2.创建一个类库EFCoreModel
3.创建一个ASP.NET Core Web 应用EFCoreWeb
设置EFCoreWeb为启动项目,为EFCoreWeb项目添加引用项目EFCoreModel。
4.设置依赖项
编辑EFCoreModel.csproj文件添加引用,此处用的是SQLserver数据库,其他数据库请稍作更改。
<ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.3" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.3" /> </ItemGroup>
同样编辑EFCoreWeb.csproj文件,添加文件的引用。
如果这种方式不会用的话,也可以使用程序包控制台命令来操作
Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools-Pre
5.创建实体,在类库项目中添加一个Models文件夹
在文件夹下创建一个User实体。
public class User { public int Id { get; set; } public string UserName { get; set; } public string Password { get; set; } }
code first 创建上下文
using EFCoreModel.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace EFCoreModel { public class EFCoreContext:DbContext { public EFCoreContext(DbContextOptions<EFCoreContext> options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); } public DbSet<User> Users { get; set; } } }
6.编辑Startup.cs
编辑public void ConfigureServices(IServiceCollection services)
添加连接数据库字符串
public void ConfigureServices(IServiceCollection services) { var connection = @"server=DESKTOP-9HM12DD\YYBSQL;database=EFCoreDemo;integrated security=SSPI;";//windows身份验证 //var connection = @"server=DESKTOP-9HM12DD\YYBSQL;database=EFCoreDemo;uid=sa;password=66666"; services.AddDbContext<EFCoreContext>(options => options.UseSqlServer(connection)); services.AddMvc(); }
7.根据实体创建数据库
在程序包管理控制台执行命令
Add-Migration EFCoreDemo
此时会在EFCoreModel下多出一个文件夹Migrations
此时数据库中还未创建表继续执行命令
Update-DataBase
至此,简单搭建EFCore完成,并成功根据实体创建数据库。