Scenes
Generally speaking, if efcore performs data migration, the steps are as follows:
- Install nuget package
- Create entity class
- Create config
- Create dbcontext
Then execute the following command to successfully migrate
-
Add-Migration Init
-
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
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