Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple DbContext classes use the same connection string?

For example, I have following DbContext classes.

public class AppDbContext : DbContext {
    ...
}
public class LogDbContext : DbContext {
    ...
}
public class FooDbContext : DbContext {
    ...
}

If a connection string named AppDbContext is on the App.Config and I want other DbContext classes to share the same connection string as AppDbContext, could I just pass the string "AppDbContext" as the parameter for the ctor of LogDbContext and FooDbContext. For example,

public class FooDbContext : DbContext {
    public FooDbContext : base("AppDbContext") { }
}

Does it have any side effects ?

Update 2013/1/9

After trying @ShinH2S's suggestion and somethings, I give up this way, and decide give different Dbcontext derived classes with different connectionStrings and database. I have try a test project and put it on GitHub. It will throw a runtime exception when the entityframework detects the database scheme is changed because the AppDbContext and FooDbContext have different schemas. If I assign a DropCreateDatabaseIfModelChanges strategy to both DbContext derived classes, one of them will be dropped because the models is different to another.

Update 2017/10

This is an old problem. In my memory, EF6 and above versions can have different migration history for multiple context in the same migration table. I prefer this answer at SO. I had not been coding with C# about 2 years.

like image 414
AechoLiu Avatar asked Jan 08 '13 08:01

AechoLiu


1 Answers

IMHO, there is no side effects. But if it was me I will just create a base class that inherits from DbContext class BaseDbContextthen all the contexts (AppDbContext, LogDbContext and FooDbContext ) will derive from BaseDbContext.

like image 83
CodeNotFound Avatar answered Oct 29 '22 18:10

CodeNotFound