简体   繁体   中英

Can I Create Two Entity Framework Contexts That Have The Exact Same Model For Both Contexts?

I have two separate sets of tables in the same database that model the exact same data but in different states. One is a live state, and the other is a staging state (not test). I am trying to create a model that will allow me to choose which datasource/datacontext to use at runtime, but they must both have the same model.

public TestObject GetTestObject(string testNum, string Environment)
{
    IDataContext context = DataContextFactory.GetContext(Environment);
    TestObject t = (from test in context.Orderable
                         where test.TestNumber == testNum
                         select test).FirstOrDefault();
    return t;
}

Obviously, based on the code above, if the Environment is Staging, I pull from a set of tables. If the Environment is Live, then I pull from a different set of tables.

So, normally with EF, I will get two separate models with different names. If I try give them the same name I get errors stating that there is already an object with that name in the project.

I have recently looked into my own POCO to consume the database, but have not been able to connect the dots to create a solution.

EDIT: Changed from "Two datasources" to "Two sets of tables in the same database". This was obviously confusing, my apologies.

Is it possible? Probably. Is it a good idea? No. Will it take more time than it's worth to make it work? Most likely.

If I'm understanding your requirements correctly, you really don't need two contexts.

You just need to swap out the connection string that is used when you instantiate your context at runtime. That will allow you to point your context at either the production or staging database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM