数据库优先是EF Core会根据数据库自动创建Entity&Context,因此首先你得先创建数据库
我们通过一个Company数据库做个演示
1 SQL Server中创建数据库
在Visual Studio中打开View->SQL Sever Object Explorer,然后创建一个简单的数据库名称为Company,在数据库中创建两个表:
Employee Department
Employee 表定义如下:
Department 表定义如下:
这两张表的Primary Key是Id列并且自增长
Department&Employee是一对多的关系,一个Department有多个Employee,我们在Employee表中创建DepartmentId列作为Department表的外键
创建表脚本
CREATE TABLE [dbo].[Department](
[Id] [int] IDENTITY(1,1) NOT ,
[Name] [varchar](50) NOT ,
CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
//Employee 表
CREATE TABLE [dbo].[Employee](
[Id] [int] IDENTITY(1,1) NOT ,
[DepartmentId] [int] NOT ,
[Name] [varchar](100) NOT ,
[Designation] [varchar](25) NOT ,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Employee] WITH CHECK ADD CONSTRAINT [FK_Employee_Department] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Department] ([Id])
GO
ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [FK_Employee_Department]
GO
2 Entity Framework Core数据库连接字符串
数据库连接字符串包含了数据源以及一些必要的连接信息,EF Core需要连接字符串和数据库进行交互,指定数据库操作像新增,读取等,打开SQL Sever Object Explorer,鼠标选中数据库,右击属性,在属性窗体中找到Connection String并且复制该值
数据库连接字符串是:
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Company;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
3 .NET Core CLI Scaffold 命令
在Package Manager Console 窗体中运行CLI Scaffold命令,在Visual Studio 中打开Tools->NuGet Package Manager->Package Manager Console 菜单
运行之前请确保你在项目中已经安装了EF Core 相关工具链,运行命令如下:
dotnet ef dbcontext scaffold "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Company;Integrated Security=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models
解释:
双引号内指定了数据库连接字符 Microsoft.EntityFrameworkCore.SqlServer指定了使用SQL Server的Provider -o Models 指定了生成Entity & Context 类的目录名称
这个命令需要执行10-20秒,执行完之后我们可以看到生成的类
3.1 Context & Entity 类
我们发现在Models 目录下生成了context & entity类
3.2 Employee类
public partial class Employee
{
public int Id { get; set; }
public int DepartmentId { get; set; }
public string Name { get; set; } = !;
public string Designation { get; set; } = !;
public virtual Department Department { get; set; } = !;
}
3.3 Department类
public partial class Department
{
public int Id { get; set; }
public string Name { get; set; } = !;
public virtual ICollection<Employee> Employees { get; } = new List<Employee>();
}
3.4 CompanyContext类
public partial class CompanyContext : DbContext
{
public CompanyContext()
{
}
public CompanyContext(DbContextOptions<CompanyContext> options)
: base(options)
{
}
public virtual DbSet<Department> Departments { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
=> optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Company;Integrated Security=True;");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>(entity =>
{
entity.ToTable("Department");
entity.Property(e => e.Name)
.HasMaxLength(50)
.IsUnicode(false);
});
modelBuilder.Entity<Employee>(entity =>
{
entity.ToTable("Employee");
entity.Property(e => e.Designation)
.HasMaxLength(25)
.IsUnicode(false);
entity.Property(e => e.Name)
.HasMaxLength(100)
.IsUnicode(false);
entity.HasOne(d => d.Department).WithMany(p => p.Employees)
.HasForeignKey(d => d.DepartmentId)
.OnDelete(DeleteBehavior.ClientSet)
.HasConstraintName("FK_Employee_Department");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
4 PMC Scaffold-DbContext 命令
我们能跳过dotnet cli scaffold 命令,在Package Manager Console 中使用Scaffold-DbContext 命令从数据库中创建Context & Entity 类,这个和上面的完全相同,在Package Manager Console 中运行如下命令
Scaffold-DbContext "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Company;Integrated Security=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
总结
这节我们主要学习 Entity Framework Core 数据库优先,以及使用脚手架命令根据数据库生成对应的Entity & Context,然而,数据库优先是不被推荐的,Microsoft建议我们使用代码优先方法 在下一节中我们将了解DbContext 类
参考资料
https://www.yogihosting.com/database-first-approach-entity-framework-core/
本文暂时没有评论,来添加一个吧(●'◡'●)