Entity Framework 5 - Extending DBContext Class

2019-07-19 16:27发布

问题:

I don't know if I'm doing something wrong here or not...

As a bit of background, I am working on an Entity Framework (v5.0) solution and was looking to add extra functionality to the DBContext class, so any tt-generated classes (that inherit from DbContext) will have that inherent functionality available to them automatically.

Based upon the answer I saw here, I figured it would be as easy as simply adding in a new class that would look as follows:

Imports System.Data.Entity
Imports System.Data.Entity.Infrastructure

Partial Public Class DbContext
    ... add in my methods / extra things here ...
End Class

But the moment I create this class, my entire solution comes up with errors related to things such as DBContext not implementing IDisposable, or errors such as sub 'OnModelCreating' cannot be declared 'Overrides' because it does not override a sub in a base class..

Basically, if I'm understanding the issue, the moment I create this, the original DBContext seems to be ignored and my solution assumes this is the only DBContext class.

That would lead me to believe that DBContext is not a partial class in its definition (which would negate the above-mentioned answer), but I'm also thinking I know too little and might just be doing something stupidly wrong.

Any help / guidance would be really appreciated!!

Also, I know this sample code was written in VB.net, but I'm equally comfortable with c# / VB.net solutions.

Thanks!!

回答1:

As is, you're creating a new class inside your own assembly called DbContext. All members (variables, properties, etc.) of type DbContext (if you haven't used a fully qualified name) will now be "mapped" to this type.

From MSDN:

You can divide the definition of a class or structure among several declarations by using the Partial keyword. You can use as many partial declarations as you want, in as many different source files as you want. However, all the declarations must be in the same assembly and the same namespace.

Your options are:

1) Subclass:

Public Class DbContextEx
    Inherits DbContext
End Class

2) Create extension methods:

Public Module DbExtensions

    <Runtime.CompilerServices.Extension()>
    Public Function Test1(source As DbContext) As Object
    End Function

    <Runtime.CompilerServices.Extension()>
    Public Sub Test2(source As DbContext)
    End Sub

End Module