Best practice for multiple data contexts for accessing different databases with different schemas #4102
-
I'm in a situation where I have to work with multiple SQL databases, each with their own schemas and domains. Example: public static class FruitConnectionExtensions
{
public static async Task EatFruits(this IDataContext fruitConnection)
{
// Do some fruit specific stuff
}
}
public static class AnimalConnectionExtensions
{
public static async Task Bark(this IDataContext, int dogId)
{
// Log that the dog barked
}
} The issue comes when both of these come into play in the same assembly, and I end up creating footguns for myself: var fruitConnection = FruitFactory.GetConnection();
var animalConnection = AnimalFactory.GetConnection();
await fruitConnection.EatFruit(); // OK
await animalConnection.Bark(2); // OK
// Error because the relevant tables don't exist in the database
// And besides this business logic doesn't make sense
await fruitConnection.Bark(2); I was hoping to get some compile time verification that I'm dealing with the correct connection, but I can't see that there's a generic public static class FruitConnectionExtensions
{
public static async Task EatFruits<TFruitTable>(this IDataContext<TFruitTable> fruitConnection)
where TFruitTable : IFruitTable
{
// Do some fruit specific stuff
}
} But the lack of a generic interface also makes me think maybe I'm barking up the wrong tree here, and what I want to do is not idiomatic. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Presumably you already have a public static class FruitConnectionExtensions
{
public static async Task EatFruits(this FruitDbContext fruitConnection)
{
// Do some fruit specific stuff
}
}
public static class AnimalConnectionExtensions
{
public static async Task Bark(this AnimalDbContext animalContext, int dogId)
{
// Log that the dog barked
}
} |
Beta Was this translation helpful? Give feedback.
Presumably you already have a
class FruitDbContext : DataConnection
and aclass AnimalDbContext : DataConnection
(which would also give you access to the tables on those connections); so you could just write the extensions: