步骤
1、新建类库项目CitiesManager.Core
为CitiesManager.WebAPI添加项目引用
CitiesManager.Core中新建文件夹Entities,将CitiesManager.WebAPI中Models下的City.cs移动到Entities,删除Models,更新City.cs中的命名空间
using System.ComponentModel.DataAnnotations;
namespace CitiesManager.Core.Entities
{
public class City
{
[Key]
public Guid CityID { get; set; }
[Required(ErrorMessage = "City Name can't be blank")]
public string? CityName { get; set; }
}
}
2、新建CitiesManager.Infrastructure类库项目
CitiesManager.Infrastructure中新建文件夹DatabaseContext,将CitiesManager.WebAPI中DatabaseContext下的ApplicationDbContext.cs移动到CitiesManager.Infrastructure中的DatabaseContext,删除CitiesManager.WebAPI中DatabaseContext,更新ApplicationDbContext.cs中的命名空间
using CitiesManager.Core.Entities;
using Microsoft.EntityFrameworkCore;
namespace CitiesManager.Infrastructure.DatabaseContext
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public ApplicationDbContext()
{
}
public virtual DbSet<City> Cities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<City>().HasData(new City[]
{
new City
{
CityID = Guid.Parse("F3D83BDE-F859-4C40-BDBE-A3ED8E48D850"),
CityName = "New York",
},
new City
{
CityID = Guid.Parse("FE331780-B359-4707-8455-016D472ED64F"),
CityName = "London",
}
});
}
}
}
并安装如下NuGet包
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.6">
将Migration文件夹剪切到CitiesManager.Infrastructure中;
CitiesManager.WebAPI添加项目引用
3、通过Build Solution找出错误的地方并修正
结果
可以正常运行程序
项目结构如下
Gitee获取源码: