问题
I am using a single database design for 3 different SQL Server locations (production, backup, master). The design is simple, shown below for the production location:
Public Class ProductionDbContext
Inherits DbContext
Public Sub New()
MyBase.New("ProductionDbConnection")
End Sub
Public Sub New(connectionString As String)
MyBase.New(connectionString)
End Sub
Public Property Tables As DbSet(Of Table) 'Table includes a List(Of Topic)
Public Property Topics As DbSet(Of Topic) 'for direct access to Topics when needed
End Class
I have initially coded 3 separate contexts according to what's above, so:
Public Class ProductionDbContext
Public Class BackupDbContext
Public Class MasterDbContext
When I access these contexts for various operations, I'd like to do something simple like:
Dim prodDb As New ProductionDbContext
Dim backupDb As New BackupDbContext
Dim masterDb As New MasterDbContext
Dim topicsList As New List(Of Topic)
LoadData(topicsList, prodDb) or
LoadData(topicsList, backupDb) or
LoadData(topicsList, masterDb)
And then LoadData is defined as something like (but this doesn't work):
Public Sub LoadData(ByRef topicsList As List(Of Topic), localContext As Object)
Dim thisTopicTable = localContext.Tables.Include("Topics").Where(Function(x) x.Property = "something").SingleOrDefault()
If thisTopicTable IsNot Nothing Then
topicsList = thisTopicTable.Topics.ToList()
End If
End Sub
This doesn't work because localContext is not defined properly to have access to the EF methods like .Where and so on.
I know my current design attempt is not correct, but I don't have the experience yet to know how I should have designed things so that the 3 different databases/dbContexts can be treated as similar objects and I don't have to "repeat myself" throughout the code.
There may be a better way to setup the 3 separate databases that I should have used, and that would be great to know (implied question 1), but I would still like to understand more deeply how I use the idea of a Type Object when passing parameters so the object can be coded in the new method the same way as the object being passed in (question 2). I don't really do a lot of that type of coding; most of my code is very type structured.
I did try to design an intermediate Class that inherits DbContext that could then be inherited by my 3 Classes listed above, but I quickly `lost the pursuit curve' on that.
来源:https://stackoverflow.com/questions/61376621/how-do-i-define-multiple-ef-dbcontexts-that-share-the-same-structure-so-they-can