Entity Framework Core 的 Cosmos 提供程序使用 DbContext 类名创建容器

问题描述 投票:0回答:2

我在 asp net core 3.1 应用程序中使用 Azure Cosmos DB 和 Microsoft.EntityFrameworkCore.Cosmos 包。在 OnModelCreating 方法的 AppContext 类中,我为每个 dbset ToContainer() 方法提供了定义容器的名称,否则它将为容器提供 AppContext 名称。一切工作正常,但它仍然在 CosmosDb 中创建一个容器 AppContext,我该如何解决这个问题?请帮忙。下面是我的代码。

AppContext 类

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace CosmosApp.Context
{
    public class AppContext : IdentityDbContext<AppUser>
    {
        public DbSet<Teacher> Teachers { get; set; }

        public DbSet<Student> Students { get; set; }

        public AppContext(DbContextOptions options)
            : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<IdentityUser>().ToContainer("Users");
            modelBuilder.Entity<AppUser>().ToContainer("Users");
            modelBuilder.Entity<IdentityUserRole<string>>().ToContainer("UserRoles");
            modelBuilder.Entity<IdentityUserLogin<string>>().ToContainer("UserLogins");
            modelBuilder.Entity<IdentityUserClaim<string>>().ToContainer("UserClaims");
            modelBuilder.Entity<IdentityRole>().ToContainer("Roles");
            modelBuilder.Entity<IdentityUserToken<string>>().ToContainer("UserTokens");

            modelBuilder.Entity<Teacher>().ToContainer("Teachers");
            modelBuilder.Entity<Student>().ToContainer("Students");
            modelBuilder.Entity<Teacher>().HasNoDiscriminator();
            modelBuilder.Entity<Student>().HasNoDiscriminator();
        }
    }
}

应用程序用户类

using Microsoft.AspNetCore.Identity;

namespace CosmosApp.Entities
{
    public class AppUser : IdentityUser
    {
        public string DisplayName { get; set; }
    }
}

创业班

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppContext>(options =>
            {
                options.UseCosmos(
                    "https://localhost:8081/",
                    "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
                    "TestDb");
            });

            services.AddControllers();

            services.AddIdentity<AppUser, IdentityRole>(options => { })
                .AddEntityFrameworkStores<AppContext>()
                .AddDefaultTokenProviders();

            services.AddAuthentication();
        }

节目课程

using System;
using CosmosApp.Context;
using CosmosApp.Entities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using AppContext = CosmosApp.Context.AppContext;

namespace CosmosApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<AppContext>();
                    var userManager = services.GetRequiredService<UserManager<AppUser>>();
                    var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
                    context.Database.EnsureCreated();
                    Seed.SeedData(context, userManager, roleManager).Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occured during migration");
                }
            }

            host.Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

套餐信息

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Cosmos" Version="3.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.2">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

</Project>

现在你可以看到它正在创建未知的容器AppContext enter image description here

c# asp.net-core entity-framework-core asp.net-identity azure-cosmosdb
2个回答
8
投票

对第一个实体使用 HasDefaultContainer,对后续实体使用

ToContainer

 protected override void OnModelCreating( ModelBuilder builder ) {
     builder.HasDefaultContainer("Users");
     builder.Entity<User>().ToContainer("Users");
     builder.Entity<Teacher>().ToContainer("Teachers");
     builder.Entity<Student>().ToContainer("Students");

 }

0
投票

接受的答案不正确并且隐藏了真正的问题。

HasDefaultContainer
只是更改 EF 用于放置所有未配置实体容器的默认容器的名称。当您设置它时,您只需说“将所有未配置的 DbSet/实体放入该容器”
您实际上缺少的是

User

中的

IdentityRoleClaim
配置。
OnModelCreating

	
© www.soinside.com 2019 - 2024. All rights reserved.