EFCore—context在其他程序集时如何进行数据迁移

 场景

 解决方案:

 代码示例:


场景

一般来说,如果efcore进行数据迁移的步骤如下

  1. 安装nuget包
  2. 创建实体类
  3. 创建config
  4. 创建dbcontext

然后执行如下命令就可以成功迁移了

  1. Add-Migration Init

  2. Update-Database

一执行,报错

Unable to create an object of type 'MyDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

 原因是这样的。因为我当前解决方案有多个程序集,然后我的context是抽出来单独放到一个类库(EFCore)中,并不在webapi下。因此报错

 解决方案:

在网上找了很多资料都没解决,最后自己误打误撞解决掉了

1.首先,启动项目,设置为WebApi

2.然后 程序包管理器控制台的默认项目,设置为context所在程序集

image.png

 3.检查Webapi是否引用上面的程序集

4.webapi也需要安装nuget包

 做完这些,再试一次,成功! 

 代码示例:

dbcontext

public class MyDbContext : DbContext
{
    public DbSet<Users> Users { get; set; }

    //注入方式配置
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }
}

config

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Model.Entitys;

namespace EFCore;

 class UsersConfig:IEntityTypeConfiguration<Users>
{
    public void Configure(EntityTypeBuilder<Users> builder)
    {
        builder.ToTable("Users");
    }
}

 实体类user

using System.ComponentModel.DataAnnotations;
using Model.Common;

namespace Model.Entitys;

/// <summary>
/// 用户
/// </summary>
public class Users : IEntity
{

    public long Id { get; set; }

    public string Name { get; set; }

    public string Password { get; set; }

}

在program中注入依赖

builder.Services.AddDbContext<MyDbContext>(p =>
{
    p.UseSqlServer(builder.Configuration.GetConnectionString("SQL"));
});

 然后按上面提到的步骤操作,成功

猜你喜欢

转载自blog.csdn.net/weixin_65243968/article/details/131797222