gpt4 book ai didi

c# - Entity Framework 5 - 扩展 DBContext 类

转载 作者:太空宇宙 更新时间:2023-11-03 10:39:02 24 4
gpt4 key购买 nike

不知道是不是我哪里做错了...

作为背景知识,我正在研究一个 Entity Framework (v5.0) 解决方案,并希望向 DBContext 类添加额外的功能,因此任何 tt 生成的类(继承来自 DbContext)将自动为它们提供该固有功能。

根据我看到的答案here ,我认为这就像简单地添加一个如下所示的新类一样简单:

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

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

但是当我创建这个类时,我的整个解决方案都出现了与诸如 DBContext not implement IDisposable 之类的错误相关的错误,或者诸如 sub 'OnModelCreating' cannot be declared '覆盖',因为它不会覆盖基类中的子类。

基本上,如果我理解这个问题,那么在我创建它的那一刻,原始 DBContext 似乎被忽略了,我的解决方案假定这是唯一 DBContext 类。

这会让我相信 DBContext 在其定义中不是分部类(这会否定上述答案),但我也认为我知道的太少,可能只是做了一些愚蠢的错误。

任何帮助/指导将不胜感激!!

此外,我知道此示例代码是用 VB.net 编写的,但我对 C#/VB.net 解决方案同样满意。

谢谢!!

最佳答案

照原样,您正在自己的程序集中创建一个名为 DbContext 的新类。 DbContext 类型(如果您没有使用完全限定名称)的所有成员(变量、属性等)现在都将“映射”到该类型。

来自 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.

您的选择是:

1) 子类:

Public Class DbContextEx
Inherits DbContext
End Class

2) 创建扩展方法:

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

关于c# - Entity Framework 5 - 扩展 DBContext 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26182012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com