在 .NET 5 中,可以使用 Entity Framework Core(EF Core)轻松地将 SQL Server 数据库注入到应用程序中。以下步骤介绍了如何实现:

  1. 添加 Microsoft.EntityFrameworkCore.SqlServer 包

    在项目中添加 Microsoft.EntityFrameworkCore.SqlServer 包,以便使用 EF Core 的 SQL Server 提供程序。

  2. 配置数据库连接字符串

    在 appsettings.json 文件中添加数据库连接字符串,例如:

    {
      "ConnectionStrings": {
        "MyAppConnection": "Server=(localdb)\mssqllocaldb;Database=MyAppDb;Trusted_Connection=True;"
      }
    }
    
  3. 在 Startup.cs 中注册数据库上下文

    在 Startup.cs 文件的 ConfigureServices 方法中,使用 AddDbContext 方法注册数据库上下文,并将连接字符串传递给 UseSqlServer 方法:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using MyApp.Models;
    
    public class Startup
    {
      public IConfiguration Configuration { get; } 
    
      public Startup(IConfiguration configuration)
      {
        Configuration = configuration;
      }
    
      public void ConfigureServices(IServiceCollection services)
      {
        services.AddDbContext<MyAppContext>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("MyAppConnection")));
      }
    
      // ...
    }
    
  4. 注入数据库上下文

    在需要使用数据库的地方,将 MyAppContext 注入到控制器或其他类中,例如:

    using MyApp.Models;
    
    public class MyController : Controller
    {
      private readonly MyAppContext _context;
    
      public MyController(MyAppContext context)
      {
        _context = context;
      }
    
      // ...
    }
    
  5. 定义模型和数据表

    在 MyAppContext 类中,可以定义模型和数据表。例如:

    using Microsoft.EntityFrameworkCore;
    
    namespace MyApp.Models
    {
      public class MyAppContext : DbContext
      {
        public MyAppContext(DbContextOptions<MyAppContext> options)
          : base(options)
        {
        }
    
        public DbSet<Customer> Customers { get; set; } 
      }
    
      public class Customer
      {
        public int Id { get; set; } 
        public string Name { get; set; } 
      }
    }
    

通过以上步骤,就可以使用 EF Core 和 SQL Server 进行数据持久化操作。 EF Core 提供了许多功能,可以简化数据库操作,例如:

  • 代码优先开发:可以直接使用 C# 代码定义模型和数据表,而不需要编写 SQL 语句。
  • 数据迁移:可以将代码中的模型更改同步到数据库中。
  • 关系映射:可以方便地将 C# 代码中的模型映射到数据库中的表。
  • 数据库查询:提供了 LINQ 查询语法,可以方便地查询数据。

了解更多关于 EF Core 的信息,请参考官方文档: https://learn.microsoft.com/en-us/ef/core/

.NET 5 中使用 Entity Framework Core 注入 SQL Server 数据库

原文地址: https://www.cveoy.top/t/topic/oKMr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录