2.Entity Framework Core配置

1.安装依赖包

工具菜单中选择NuGet包管理器程序包管理器控制台 (PMC) 或 从项目菜单中选择管理NuGet程序包dotnet CLI

1.1安装EF Core数据库提供程序

安装EF Core数据库提供程序会安装 数据库驱动 和 EF Core运行时。

//SQL Server
//PMC
Install-Package Microsoft.EntityFrameworkCore.SqlServer

//CLI
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
//MySQL
//PMC
Install-Package Pomelo.EntityFrameworkCore.MySql

//CLI
dotnet add package Pomelo.EntityFrameworkCore.MySql

1.2安装 EF Core 工具

//PMC
Install-Package Microsoft.EntityFrameworkCore.Tools

//CLI
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design

1.3安装检测和诊断 EF Core 迁移错误的中间件

Install-Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore

2.数据库连接字符串

在 appsettings.json 文件中读取数据库连接字符串。

//SQL Server
"ConnectionStrings": {
    "SchoolContext": "Server=(localdb)\\mssqllocaldb;Database=SchoolContext-568d112b-dfd0-4be1-b34b-0f56e9b2a475;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
//Mysql
"ConnectionStrings": {
    "SchoolContext": "server=YOURSERVER;user=YOURUSERID;password=YOURPASSWORD;database=YOURDATABASE"
    }

3.新建实体模型

右键单击Models文件夹-添加-名称单数Blog.csPost.cs

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public int Rating { get; set; }
    public List<Post> Posts { get; set; }
}
public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

4.创建数据库上下文

在项目文件夹中,创建名为 Data 文件夹,在 Data 文件夹中,创建 SchoolContext.cs 类。

表名默认和 DbSet 属性名相同,通常采用复数形式。 例如,使用 Students,而不使用 Student。 

using ContosoUniversity.Models;
using Microsoft.EntityFrameworkCore;

namespace ContosoUniversity.Data
{
    public class SchoolContext : DbContext
    {
        public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
        {
        }

        public DbSet<Course> Courses { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Student> Students { get; set; }
    }
}

5.注册服务

//SQL Server
builder.Services.AddDbContext<SchoolContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("SchoolContext")));
//MySQL
var connectionString = builder.Configuration.GetConnectionString("SchoolContext");

var serverVersion = new MySqlServerVersion(new Version(8, 0, 29));
或者
var serverVersion = ServerVersion.AutoDetect(connectionString);

builder.Services.AddDbContext<SchoolContext>(options =>
    options.UseMySql(connectionString, serverVersion));
//添加数据库异常筛选器
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/csharp/entityframeworkcore/14607.html

(0)
上一篇 2022年6月1日 23:04
下一篇 2022年6月2日 20:53

相关推荐

发表回复

登录后才能评论