Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7758579
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T13:23:50+00:00 2026-06-01T13:23:50+00:00

I have a DbContext that is empty. Mappings are created dynamically and the DbContext

  • 0

I have a DbContext that is empty. Mappings are created dynamically and the DbContext is used generically using Set();

The following is my generic DbContext.

/// <summary>
/// Object context
/// </summary>
public class MethodObjectContext : DbContext, IDbContext
{
    private readonly IEventPublisher _eventPublisher;

    public MethodObjectContext(string nameOrConnectionString, IEventPublisher eventPublisher)
        : base(nameOrConnectionString)
    {
        _eventPublisher = eventPublisher;
    }

    public MethodObjectContext(DbConnection existingConnection, bool contextOwnsConnection, IEventPublisher eventPublisher)
        : base(existingConnection, contextOwnsConnection)
    {
        _eventPublisher = eventPublisher;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        _eventPublisher.Publish(new ModelCreating(modelBuilder));
        base.OnModelCreating(modelBuilder);
    }

    public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
    {
        return base.Set<TEntity>();
    }
}

I am trying write a unit test that will assert that the database is out of sync if I change the mappings (from the ModelCreating event).

The following is my test code.

[TestClass]
public class MigrationTests
{
    private string _connectionString = string.Empty;
    private string _testDb = string.Empty;

    public MigrationTests()
    {
        _testDb = Path.Combine("C:\\", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.Replace(".", "") + ".sdf");

        if (File.Exists(_testDb))
            File.Delete(_testDb);

        _connectionString = string.Format("Data Source={0};Persist Security Info=False;", _testDb);

        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
    }

    [TestMethod]
    public void ThrowsErrorForOutOfDateDatabase()
    {
        // The initializer will handle migrating the database. 
        // If ctor param is false, auto migration is off and an error will be throw saying the database is out of date.
        Database.SetInitializer(new MigrationDatabaseInitializer<MethodObjectContext>(false));

        // Create the initial database and do a query.
        // This will create the database with the conventions of the Product1 type.
        TryQueryType<Product1>("Product");

        // The next query will create a new model that has conventions for the product2 type.
        // It has an additional property which makes the database (created from previous query) out of date.
        // An error should be thrown indicating that the database is out of sync.
        ExceptionAssert.Throws<InvalidOperationException>(() => TryQueryType<Product2>("Product"));
    }

    private void TryQueryType<T>(string tableName) where T : class
    {
        using (var context = new MethodObjectContext(_connectionString, new FakeEventPublisher(x => x.ModelBuilder.Entity<T>().ToTable(tableName))))
        {
            var respository = new EfRepository<T>(context);
            var items = respository.Table.ToList();
        }
    }
}

My Product1 class is a POCO object, and my Product2 class is the same object with an additional db field.

My problem is that when I new() up the MethodObjectContext the second time and do a query, the ModelCreating method isn’t called, causing me to get the following error.

The entity type Product2 is not part of the model for the current context.

Product2 would be a part of the context of the ModelCreating event was being called, but it is not. Any ideas?

NOTE: I am expecting errors since we are using the same connection string (sdf) and the db being created didn’t create the additional field that my second call (Product2) requires.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T13:23:51+00:00Added an answer on June 1, 2026 at 1:23 pm

    My DbCompiledModel was being cached. The following flushed the cache.

    private void ClearDbCompiledModelCache()
    {
        var type = Type.GetType("System.Data.Entity.Internal.LazyInternalContext, EntityFramework");
        var cmField = type.GetField("CachedModels",System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
        var cachedModels = cmField.GetValue(null);
        cachedModels.GetType().InvokeMember("Clear", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod, null, cachedModels, null);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have created an IDbContext object that is provided to my IRepository implementations. The
I have created an interface that my DbContext class implements, this enables me to
I have created a context class that implements DbContext BeerRecommenderContext and an intializer that
I have a DbContext with several of the following type of members: public DbSet<JobLevel>
I have the following DbContext , where each DbSet marked with a // This
I am following the database approach first; I have created the tables in my
I have an application that contains methods that work with data using Entity Framework
I have an html.TextArea helper that I'd like to set a default. @Html.TextAreaFor(model =>
Using Entity Framework 4 CTP5 I have a basic model and a basic DbContext
I am using DBContext and have two classes whose properties are all virtual. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.