How do I define multiple EF DbContexts that share the same structure so they can use methods interchangeably?

落花浮王杯 提交于 2021-01-29 16:00:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!