You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC5多连接字符串报错:实体类型不在当前上下文模型中

Fixing "The entity type is not part of the model for the current context" with Multiple DbContexts in ASP.NET MVC5

Hey there! I see you're new to ASP.NET MVC5 and hit a roadblock with your second DbContext—that error message pops up when Entity Framework can't connect your entities to the right context, so let's walk through the most likely fixes step by step.

First, Let's Recap Your Setup

You've got two separate contexts:

  • Working: ChenvelIntlContext linked to the chenvelintlconnstring connection string
  • Broken: ChenvelJapanContext linked to chenveljapanconnstring

You're using Ninject for dependency injection, and loading entity configurations via reflection in each context's OnModelCreating method.

Common Causes & Fixes

1. Verify Entity Configuration Base Class Matching

Your ChenvelJapanContext is specifically looking for configuration classes that inherit from ChenvelJapanEntityTypeConfiguration<>. Double-check that every entity tied to the Japanese database has a configuration class that explicitly uses this base class—not ChenvelIntlEntityTypeConfiguration<>. A single misconfigured entity here will trigger the error.

2. Add Explicit DbSet Properties to Your Context

Even with configuration classes, EF sometimes needs explicit DbSet declarations to recognize entities. For every entity in your Japanese database, add a corresponding DbSet to ChenvelJapanContext:

public class ChenvelJapanContext : DbContext 
{ 
    public ChenvelJapanContext() : base("name=chenveljapanconnstring") { } 

    // Add these lines for each Japanese entity (replace with your actual entity names)
    public DbSet<JapaneseCustomer> JapaneseCustomers { get; set; }
    public DbSet<JapaneseOrder> JapaneseOrders { get; set; }
    // ... rest of your entities

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
        // Your existing reflection code here
        var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() 
            .Where(type => !string.IsNullOrEmpty(type.Namespace)) 
            .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(ChenvelJapanEntityTypeConfiguration<>)); 
        foreach(var type in typesToRegister) 
        { 
            dynamic configurationInstance = Activator.CreateInstance(type); 
            modelBuilder.Configurations.Add(configurationInstance); 
        } 
        base.OnModelCreating(modelBuilder); 
    } 
}

3. Debug the Reflection Logic in OnModelCreating

Drop a breakpoint in the OnModelCreating method of ChenvelJapanContext and check if typesToRegister actually includes all your Japanese entity configurations. If it's empty or missing some, your reflection filter might be off:

  • Confirm the namespace of your Japanese configuration classes matches the filter (no typos!)
  • Simplify the filter by targeting the exact namespace where your Japan configurations live:
    var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
        .Where(type => type.Namespace == "YourProject.Configurations.Japan") // Replace with your actual namespace
        .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(ChenvelJapanEntityTypeConfiguration<>));
    

4. Ensure Ninject Injects the Correct Context

Check your service classes (like CSI_DataService, which seems tied to the Japanese context) to make sure they depend on ChenvelJapanContext, not ChenvelIntlContext. For example:

public class CSI_DataService : ICSI_DataService
{
    private readonly ChenvelJapanContext _context;

    public CSI_DataService(ChenvelJapanContext context)
    {
        _context = context;
    }

    // Your service methods here
}

If your service uses the wrong context, EF will look for the entity in the Intl model (where it doesn't exist) and throw the error.

5. Clean & Regenerate Your Project

Sometimes EF's model cache gets corrupted. Try these steps:

  • Delete the bin and obj folders in your project
  • Clean the solution (Build → Clean Solution)
  • Rebuild the solution (Build → Rebuild Solution)

Your Original Code for Reference

Non-Working Second Context

public class ChenvelJapanContext : DbContext 
{ 
    public ChenvelJapanContext() : base("name=chenveljapanconnstring") { } 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
        var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() 
            .Where(type => !string.IsNullOrEmpty(type.Namespace)) 
            .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(ChenvelJapanEntityTypeConfiguration<>)); 
        foreach(var type in typesToRegister) 
        { 
            dynamic configurationInstance = Activator.CreateInstance(type); 
            modelBuilder.Configurations.Add(configurationInstance); 
        } 
        base.OnModelCreating(modelBuilder); 
    } 
}

Working First Context

public class ChenvelIntlContext : DbContext 
{ 
    public ChenvelIntlContext() : base("name=chenvelintlconnstring") { } 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
        var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() 
            .Where(type => !string.IsNullOrEmpty(type.Namespace)) 
            .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(ChenvelIntlEntityTypeConfiguration<>)); 
        foreach(var type in typesToRegister) 
        { 
            dynamic configurationInstance = Activator.CreateInstance(type); 
            modelBuilder.Configurations.Add(configurationInstance); 
        } 
        base.OnModelCreating(modelBuilder); 
    } 
}

Connection Strings

<connectionStrings>
    <add name="chenvelintlconnstring" connectionString="data source=server;initial catalog=chenvel_intl;persist security info=True;user id=sa;password=secret;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
    <add name="chenveljapanconnstring" connectionString="data source=server;initial catalog=chenvel;persist security info=True;user id=sa;password=secret;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
</connectionStrings>

Ninject Configuration in App_Start

public static class NinjectWebCommon 
{ 
    private static readonly Bootstrapper bootstrapper = new Bootstrapper(); 
    /// <summary> 
    /// Starts the application 
    /// </summary> 
    public static void Start() 
    { 
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); 
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); 
        bootstrapper.Initialize(CreateKernel); 
    } 
    /// <summary> 
    /// Stops the application. 
    /// </summary> 
    public static void Stop() 
    { 
        bootstrapper.ShutDown(); 
    } 
    /// <summary> 
    /// Creates the kernel that will manage your application. 
    /// </summary> 
    /// <returns>The created kernel.</returns> 
    private static IKernel CreateKernel() 
    { 
        var kernel = new StandardKernel(); 
        try 
        { 
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); 
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); 
            RegisterServices(kernel); 
            return kernel; 
        } 
        catch 
        { 
            kernel.Dispose(); 
            throw; 
        } 
    } 
    /// <summary> 
    /// Load your modules or register your services here! 
    /// </summary> 
    /// <param name="kernel">The kernel.</param> 
    private static void RegisterServices(IKernel kernel) 
    { 
        kernel.Bind<IUnitOfWork>().To<UnitOfWork>(); 
        kernel.Bind<IUserService>().To<UserService>(); 
        kernel.Bind<IUserInRoleService>().To<UserInRoleService>(); 
        kernel.Bind<IRoleService>().To<RoleService>(); 
        kernel.Bind<IClientService>().To<ClientService>(); 
        kernel.Bind<ICountryService>().To<CountryService>(); 
        kernel.Bind<IStateService>().To<StateService>(); 
        kernel.Bind<ICityService>().To<CityService>(); 
        kernel.Bind<ITownService>().To<TownService>(); 
        kernel.Bind<IPackageService>().To<PackageService>(); 
        kernel.Bind<IOrderService>().To<OrderService>(); 
        kernel.Bind<IRateService>().To<RateService>(); 
        kernel.Bind<IRateItemService>().To<RateItemService>(); 
        kernel.Bind<ICommissionService>().To<CommissionService>(); 
        kernel.Bind<IReceiverService>().To<ReceiverService>(); 
        kernel.Bind<IEmptyBoxService>().To<EmptyBoxService>(); 
        kernel.Bind<ITransactionService>().To<TransactionService>(); 
        kernel.Bind<IShipmentService>().To<ShipmentService>(); 
        kernel.Bind<IShipmentItemService>().To<ShipmentItemService>(); 
        kernel.Bind<IEmployeeService>().To<EmployeeService>(); 
        kernel.Bind<IDesignationService>().To<DesignationService>(); 
        kernel.Bind<IDeliveryService>().To<DeliveryService>(); 
        kernel.Bind<IDeliveryItemService>().To<DeliveryItemService>(); 
        kernel.Bind<IAdditionalChargeService>().To<AdditionalChargeService>(); 
        kernel.Bind<ICSI_DataService>().To<CSI_DataService>(); 
    } 
}

内容的提问来源于stack exchange,提问作者Denmark Del Puso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:13:31