【问题标题】:.NET 6 uses EF CORE to migrate.NET 6 使用 EF CORE 进行迁移
【发布时间】:2021-12-29 11:18:35
【问题描述】:

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

【问题讨论】:

  • “但我无法使用 EF Core 进行迁移”。为什么?

标签: entity-framework asp.net-core migration .net-6.0


【解决方案1】:

无法使用 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配置类的,在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

【讨论】:

猜你喜欢
  • 2022-07-15
  • 2021-12-25
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 2021-09-29
  • 2018-10-24
  • 2021-11-23
相关资源
最近更新 更多