ASP.NET Core Blazor 1:创建准备项目

  本章将创建贯穿这一部分的示例项目。

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&#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值