繁体   English   中英

C# 实体框架核心:无法解析服务

[英]C# Entity Framework Core: unable to resolve service

我第一次尝试将 Entity Framework Core 用于 C#。 我的项目确实编译了,但我的添加迁移没有运行。

我得到错误:

尝试激活“MySql.EntityFrameworkCore.Storage.Internal.MySQLTypeMappingSource”时无法解析“Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceDependencies”类型的服务。

我的项目文件:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BCrypt.Net-Next" Version="4.0.2" />
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="MySql.EntityFrameworkCore" Version="6.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>

我的数据库上下文:

internal class DbModelContext : DbContext
{
    public DbSet<DbUser> Users { get; set; }    
    public DbModelContext(DbContextOptions<DbModelContext> options)
        : base(options) { }
}

我的用户表:

internal class DbUser
{
    [Key]
    public string? Email { get; set; }
    public string? PasswordHash { get; set; }
    public Guid UserId { get; set; }
}

这是我的 Program.cs(我使用 net6,所以我没有 startup.cs)

//Init DbConnectorClass
DatabaseConnector dbConnector = new();

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//TODO: move to appsettings.json
var connString = "server=192.168.178.XXX;user=XXX;database=XXX;password=XXX;port=3306";

builder.Services.AddDbContext<DbModelContext>(options => options.UseMySQL(connString));
builder.Services.AddScoped<IAuthenticationHandler>(ah => new AuthenticationHandler(dbConnector));

WebApplication app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

如果您正确设置数据库,请尝试使用此命令“dotnet ef migrations add Initial”进行更新尝试“dotnet ef database update”

"

<PackageReference Include="EntityFramework" Version="6.4.4" />
public class MysqlEntityFrameworkDesignTimeServices : IDesignTimeServices
{
    public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
    {
        serviceCollection.AddEntityFrameworkMySQL();
        new EntityFrameworkRelationalDesignServicesBuilder(serviceCollection)
            .TryAddCoreServices();
    }
}

您可以在 startup.cs 文件中添加另一个 class 以解决此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM