本章将创建贯穿这一部分的示例项目。
1 创建项目
dotnet new globaljson --sdk-version 3.1.101 --output MyAdvanced
dotnet new web --no-https --output MyAdvanced --framework netcoreapp3.1
dotnet new sln -o MyAdvanced
dotnet sln MyAdvanced add MyAdvanced
向项目中添加 NuGet 包
dotnet add package Microsoft.EntityFrameworkCore.Design --version 3.1.1
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 3.1.1
安装全局工具包
dotnet tool uninstall --global dotnet-ef
dotnet tool install --global dotnet-ef --version 3.1.1
2 添加数据模型
这个应用程序的数据模型由三个类组成,分别代表人员、工作部门和位置。创建一个 Model 文件夹,并向其中添加一个名为 Person.cs 的类文件。
public class Person
{
public long PersonId { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
public long DepartmentId { get; set; }
public long LocationId { get; set; }
public Department Department { get; set; }
public Location Location { get; set; }
}
将一个名为 Department.cs 的类文件添加到 Models 文件夹中。
public class Department
{
public long Departmentid { get; set; }
public string Name { get; set; }
public IEnumerable<Person> People { get; set; }
}
在 Models 文件夹中添加一个名为 Location.cs 的类文件。
public class Location
{
public long LocationId { get; set; }
public string City { get; set; }
public string State { get; set; }
public IEnumerable<Person> People { get; set; }
}
要创建提供对数据库的访问的 EF Core 的上下文类, Models 文件夹添加 DataContext.cs。
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> opts)
: base(opts) { }
public DbSet<Person> People { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Location> Locations { get; set; }
}
2.1 准备种子数据
将一个名为 SeedData.cs 的类添加到 Models 文件夹中,以定义用于填充数据库的种子数据。
public static class SeedData
{
public static void SeedDatabase(DataContext context)
{
context.Database.Migrate();
if (context.People.Count() == 0 && context.Departments.Count() == 0 &&
context.Locations.Count() == 0)
{
Department d1 = new Department { Name = "Sales" };
Department d2 = new Department { Name = "Development" };
Department d3 = new Department { Name = "Support" };
Department d4 = new Department { Name = "Facilities" };
context.Departments.AddRange(d1, d2, d3, d4);
context.SaveChanges();
Location l1 = new Location { City = "Oakland", State = "CA" };
Location l2 = new Location { City = "San Jose", State = "CA&#