ASP.NET Core 中使用EF Core 将实体映射到数据库表的方法(SQL Server)
前段时间听过一个关于使用ASP.NET Core建立项目的视频。其中使用EF Core映射到数据库的部分是按部就班地学习。今天自己建立项目时,有些步骤已经有一些遗忘。所以写下这篇文章,顺便理清思路。
新建项目后:
1、Models文件夹下建立实体类,如User
public class User { public int Id { get; set; } public int Account { get; set; } public int Password { get; set; } }
2、建立数据库上下文类XXXXXDbContext,建议直接在项目根目录下建立文件夹EntityFramework,将这个类文件置于该路径下
public class SchoolDbContext : DbContext { public SchoolDbContext(DbContextOptions<SchoolDbContext> options):base(options) { } public DbSet<User> Users { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<User>().ToTable("t_user"); } }
modelBuilder.Entity<User>().ToTable("t_user")表示实体User映射到数据库中的表名称为t_user
3、在Startup.cs文件的ConfigureServices方法中注入数据库上下文
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//注入
services.AddDbContext<SchoolDbContext>(d => d.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
其中的Configuration.GetConnectionString("DefaultConnection")的意思是获取配置文件中名称为"DefaultConnection"的连接字符串。可在appsettings.json文件中添加该连接串:
{ "ConnectionStrings": { "DefaultConnection": "Data Source=localhost;Database=SchoolManageSystem;User ID=sa;Password=Sa;" }, "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*" }
4、在Nuget的程序包管理控制台下依次输入add-migration First_Migration、update-database,将实体类映射到数据库。使用数据库查看工具,即可看到数据库中已经生成了名为t_user的表。