How to migrate data when EFCore-context is in other assemblies

 Scenes

 solution:

 Code example:


Scenes

Generally speaking, if efcore performs data migration, the steps are as follows:

  1. Install nuget package
  2. Create entity class
  3. Create config
  4. Create dbcontext

Then execute the following command to successfully migrate

  1. Add-Migration Init

  2. Update-Database

Once executed, an error is reported

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

 The reason is this. Because my current solution has multiple assemblies, and my context is extracted and placed in a separate class library (EFCore), not under the webapi. Therefore an error is reported

 solution:

I searched a lot of information on the Internet but couldn't solve it. Finally I solved it by mistake.

1. First, start the project and set it to WebApi

2. Then set the default project of the package manager console to the assembly where the context is located

image.png

 3. Check whether Webapi references the above assembly

4.webapi also needs to install the nuget package

 After doing this, try again, success! 

 Code example:

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");
    }
}

 Entity class 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; }

}

Inject dependencies into the program

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

 Then follow the steps mentioned above, success

Guess you like

Origin blog.csdn.net/weixin_65243968/article/details/131797222