簡體   English   中英

.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));

Model:

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM