1

Some background: We sell an online product and each customer gets their own database but are using a shared service.

I would like to use EF6 instead of old ADO.NET, But as far as I know it's not possible to change the database when the dbcontext is created, and i fear that it's too expensive to create a new dbcontext for each query.

And caching 1000+ dbcontext's sounds like a very bad solution.

0

4 Answers 4

1

Connection pooling will not work well with 1000+ connection strings. There will be one pool for each database resulting in an enormous amount of connections.

I recommend that you connect to a dummy database first, then use DbConnection.ChangeDatabase to change into the right database. EF does not notice that and works just fine.

You don't need to cache DbContext's. They are lightweight.

Sign up to request clarification or add additional context in comments.

Comments

1

This is actually pretty easy to do

public class MyContext : DbContext{ public MyContext(string connectionStringName): base(connectionStringName){} } 

or

public class MyContext : DbContext{ public MyContext(DbConnection connection): base(connection, contextOwnsConnection: true){} } 

2 Comments

+1 I use the approach Luke suggests for a multi-tenancy model
On the note about connection pooling, if you set the second constructor and use contextownsconnection false you can reuse the connection. You probably need mars to do this as well
0

You should not be too concerned about the cost of construction of DbContext. There are other factors to consider in deciding the lifetime of your DbContext/ObjectContext, which you can find here.

It's not a good idea to share your DbContext instance primarily because of Memory Usage and Thread Safety as mentioned in the above link.

Comments

0

You can do next:

public class BaseContext<TContext> : DbContext where TContext : DbContext { protected BaseContext(): base("name=DbName") { } } 

And that use it like this:

 public class StatusContext : BaseContext<StatusContext> { .... } 

All contexts that inherit from BaseContext will use same db.

1 Comment

So if I have 100 identical database I will not get into trouble using a new connection string for each http request?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.