.NET 6 使用 EF CORE 迁移

.NET 6 uses EF CORE to migrate

我已经将.NET版本升级到最新的6.0,但是无法使用EF Core迁移。版本的变化让我感觉很陌生,资料也比较少。您提供的任何信息或帮助都很棒!

无法使用EF Core迁移是什么问题?对于.net6版本,迁移变化不是很大。我根据一些资料写了一个简单的demo,希望对你有所帮助

csproj 文件:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

</Project>

然后在appsettings.json中添加数据库连接配置:

"ConnectionStrings": {
    "DefaultConnection": "Your Db"
  }

然后在.net6版本中,没有Startup.cs配置class,在Program.cs中做了一些配置:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();


var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<UserContext>(options => options.UseSqlServer(connectionString));

型号:

 public class User
    {

        [Key]
        public int Id { get; set; }

        public string Name { get; set; }

       public DateTime CreatedDate { get; set; }
      
    }

创建上下文:

 public class UserContext:DbContext
    {
        public UserContext(DbContextOptions<UserContext> options) : base(options) { }
        public DbSet<User> Users { get; set; }
    }

然后使用迁移命令:

add-migration MigrationName
update-database

测试:

 public class TestController : Controller
    {
        private readonly UserContext _context;

        public TestController(UserContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            User user = new User();
            user.Name ="Test";
            user.CreatedDate = DateTime.Now;
               _context.Add(user);
              _context.SaveChanges();                  
            return View();
        }
    }

结果:

我以代码优先迁移为例。如果按照步骤有问题,可以把错误发出来,也可以把现在遇到的错误发出来,可以看看.net6的一些改动:

https://gist.github.com/davidfowl/0e0372c3c1d895c3ce195ba983b1e03d