在 Entity Framework Core 中使用 SQLServer
admin
2021-06-03本文作者:梁桐铭- 微软最有价值专家(Microsoft MVP)
本文出自《从零开始学 ASP.NET Core 与 EntityFramework Core》目录
视频课程效果更佳:跨平台开发实战掌握 ASP.NET Core 与 EntityFramework Core
在 Entity Framework Core 中使用 SQLServer
在本章节中,我们将学习如何使用 Entity Framework Core 配置和使用 SQLServer。
使用 Entity Framework Core 时,我们需要配置的重要事项之一就是配置我们计划使用的数据库提供程序。 Entity Framework Core 支持各种各样的数据库,包括非关系数据库。以下 MSDN 链接具有所有受支持的数据库的列表。
https://docs.microsoft.com/zh-cn/ef/core/providers/
public class Startup
{
private IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AppDbContext>(
options => options.UseSqlServer(_config.GetConnectionString("StudentDBConnection")));
services.AddMvc().AddXmlSerializerFormatters();
services.AddTransient<IStudentRepository, MockStudentRepository>();
}
//其他代码
}
- 我们希望使用 Entity Framework Core 配置和使用 Microsoft SQLServer。
- 我们通常在 Startup.cs 文件的 ConfigureServices()方法中指定此配置。
AddDbContext()和 AddDbContextPool()方法之间的区别
- 我们可以使用 **AddDbContext()或AddDbContextPool()**方法向 ASP.NET Core 依赖注入容器中注册我们的应用程序特定的 DbContext 类。
- AddDbContext()和 AddDbContextPool()方法的区别在于,AddDbContextPool()方法提供了 数据库连接池(DbContextPool)。
- 使用数据库连接池,如果可用,则提供数据库连接池中的实例,而不是创建新实例。
- 数据库连接池在概念上类似于 ADO.NET 中连接池的工作方式。
- 从性能角度来看,AddDbContextPool()方法优于 AddDbContext()方法。
- ASP.NET Core 2.0 中引入了 AddDbContextPool()方法。因此,如果您使用的是 ASP.NET Core 2.0 或更高版本,则推荐使用 AddDbContextPool()方法而不是 AddDbContext()方法。
UseSqlServer()扩展方法
UseSqlServer()扩展方法用于配置我们的应用程序特定的 DbContext 类,以使用 Microsoft SQLServer 作为数据库。 要连接到数据库,我们需要将数据库连接字符串作为的参数,添加到 UseSqlServer()扩展方法中。
services.AddDbContextPool<AppDbContext>(
options => options.UseSqlServer(_config.GetConnectionString("StudentDBConnection")));
ASP.NET Core 中的数据库连接字符串
我们不需要在应用程序代码中对连接字符串进行硬编码,而是将其存储在 appsettings.json
配置文件中。
{
"ConnectionStrings": {
"StudentDBConnection": "server=(localdb)\\MSSQLLocalDB;database=StudentDB;Trusted_Connection=true"
}
}
在传统的 ASP.NET 中,我们将应用程序配置存储在 XML 格式的 web.config 文件中。在 ASP.NET Core 中,需要采用不同的配置源。这个配置源就是 appsettings.json 文件,它是 JSON 格式。
而要从 appsettings.json 文件中读取连接字符串,我们使用 IConfiguration
服务 中的GetConnectionString()
方法。
我们使用的 SQLServer localdb 与 Visual Studio 一起自动安装。如果要使用完整的 SQLServer 而不是 localdb,只需将 appsettings.json 配置文件中的连接字符串更改为指向 SQLServer 实例即可。
//访问本地的数据库
"server=(localdb)\\MSSQLLocalDB;database=StudentDB;Trusted_Connection=true"
//访问完整的SQL链接字符串
"Server=localhost; Database=EmployeeDB; Trusted_Connection=True;"
数据库连接字符串中的内容之间有什么区别:
- Trusted_Connection=True;
- Integrated Security=SSPI;
- Integrated Security=true;
以上 3 个设置都代表一个相同的内容,使用集成 Windows 身份验证连接到 SQLServer 而不是使用 SQLServer 身份验证。
目前我们的应用程序仍在使用 MockEmployeeRepository,它是内存中的学生集合。在我们的下一个视频中,我们将实现 SQLRepository,它存储和查询我们刚刚配置的 SQLServer localdb 中的学生信息。
文章说明
如果您觉得我的文章质量还不错,欢迎打赏,也可以订阅我的视频哦
未得到授权不得擅自转载本文内容,52abp.com 保留版权
感谢您对我的支持