Link to home
Start Free TrialLog in
Avatar of troycomp
troycomp

asked on

Dynamically changing connections with the ADO.NET Entity Framework

I have a .net 4 web application that has numerous ADO.NET entity framework models. These models are all the same sans the data thats in them. We will eventually combine all the databases into one, but thats way down the road. In the meantime i have multiple models.

The user will select a client from a dropdown list, and then the app will show data for that client. They can choose another client at anytime. Is there a way to dynamically change which model you want to pull dala from? Let me elaborate.

One of my models is called fnshipModel.edmx, another is esshipModel. I dont want to write code like this:

if (client == "fnship") {
var data = new fnshipEntities();
// do some work here
}

else if (client == "esship"){
var data = new esshipEntities();
// do the samework here just look at a different model
}

So forth and so on. I would like to do it like this:

SomeObjectThatTheEntityFrameworkUsesWhenItsBeingCreated data = null;

if (cleint == "fnship")
      data = new fnshipEntity();
else if (cleint == "esship")
     data = new esshipEntity();

RunOneSetOfCode(data);

private void RunOneSetOfCode(SomeObjectThatTheEntityFrameworkUsesWhenItsBeingCreated  data)
{
use data anyway i like and if i need to make a change, i change it in one place and not in multiple places
}

Is this possible?
Avatar of Rouneh10
Rouneh10

The Entities inherit from ObjectContext. Have you tried using that?

   ObjectContext Data;
   if (client == "fnship")
      Data = new fnshipEntities();
   else if (client == "esship")
      Data = new esshipEntities();

   RunOneSetOfCode(Data);

   private void RunOneSetOfCode(ObjectContext Data)
   {
       // Do stuff here
   }

Open in new window

Avatar of troycomp

ASKER

I tried that and that doesnt work. When i do this:

     var data = new fnshipEntities();
      foreach (var product in data.Products)
      {
                        var x = product.ProductId;
      }      

It works like a charm. But when I try it your way, and i thought this would work:
      ObjectContext data = null;
      data = new fnshipEntities();

    foreach (var product in data.Products) <-- compiler error cannot resolve symbol Products
    {
        var x = product.ProductDescription;
    }      

It doesnt see my tables or anything. Maybe the entity framework was written this way on purpose. But this seems weird to me. The entity framework is just a class like any other class and should behave the same
ASKER CERTIFIED SOLUTION
Avatar of Rouneh10
Rouneh10

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You are the man. Thank you so much