.net core 2.0 数据访问-迁移

将用于进行迁移的 Entity Framework Core NuGet包 添加到`.csproj`文件
 <ItemGroup>
        <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
        //<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" /> 此处做个代码标识,以便知道代码添加位置
    </ItemGroup>
更改连接字符串 *`appsettings.json`*
{
        "ConnectionStrings": {
            "MySqlConnection": "Data Source=.;Database=Blog;User ID=hh;Password=hh;pooling=true;CharSet=utf8;port=3306;sslmode=none"
        },
修改`Startup.cs`文件中的`ConfigureServices`方法
  使用mysql前提,添加`Pomelo.EntityFrameworkCore.MySql`,在`project.csproj`文件中添加`<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.1" />`
//获取连接字符串
    var connection = Configuration.GetConnectionString("MySqlConnection");
    //注册上下文
    services.AddDbContext<BlogContext>(options => options.UseMySql(connection));
创建实体类(与数据库表对应,多对多关系,需要建立第三张表,包含两张主表主键和对象,并且两张主表中有第三张表的集合)
  • 假如主表是A和B,第三张表是C
  • A表结构:主键,其他字段,C表集合
  • B表结构:主键,其他字段,C表集合
  • C表结构:A主键,A实体对象,B主键,B实体对象
创建DBContext类,并注册实体
public class BlogContext:DbContext
    {
        public DbSet<UserInfo> UserInfo { get; set; }
        public DbSet<RoleInfo> RoleInfo { get; set; }
        public DbSet<ActionInfo> ActionInfo { get; set; }
        public DbSet<UserRole> UserRole { get; set; }
        public DbSet<UserAction> UserAction { get; set; }
        public DbSet<RoleAction> RoleAction { get; set; }
        //组合键
        protected override void OnModelCreating(ModelBuilder modelBuilder){
            modelBuilder.Entity<UserRole>().HasKey(u=>new{u.UserInfoID,u.RoleInfoID});
            modelBuilder.Entity<RoleAction>().HasKey(u=>new{u.RoleInfoID,u.ActionInfoID});
            modelBuilder.Entity<UserAction>().HasKey(u=>new{u.UserInfoID,u.ActionInfoID});
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseMySql("connectionstring");
        }
    }
  1. 删除迁移 dotnet ef database drop
  2. 添加迁移 dotnet ef migrations add 迁移名
  3. 更新迁移到数据库 dotnet ef database update
原文地址:https://www.cnblogs.com/xiaonangua/p/9176465.html