Cosmos provider for Entity Framework Core creating container with DbContext class name

asp.net-core asp.net-identity azure-cosmosdb c# entity-framework-core

Question

I'm using Azure Cosmos DB in asp net core 3.1 app with Microsoft.EntityFrameworkCore.Cosmos package. In my AppContext class on OnModelCreating method i've give every dbset ToContainer() method to define the name of container otherwise it'll give AppContext name to container. Everything is working fine but it still create one container AppContext in CosmosDb, how can i fix this? Please help. Below is my code.

AppContext Class

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

AppUser Class

using Microsoft.AspNetCore.Identity;

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

Startup Class

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

Program Class

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

Packages Info

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

Now you can see it was creating unknown conatiner AppContext enter image description here

1
0
3/22/2020 6:49:15 AM

Accepted Answer

Use HasDefaultContainer for the first Entity and ToContainer on subsuquent Entities.

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

 }
1
3/22/2020 11:11:05 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow