簡體   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