Entity Framework 5 - Extending DBContext Class

匆匆过客 提交于 2019-12-24 03:07:39

问题


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


来源:https://stackoverflow.com/questions/26182012/entity-framework-5-extending-dbcontext-class

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