如何在给定 DbCommand 或 DbConnection 的情况下创建 DbDataAdapter?
我想创建一个可与任何数据提供者一起使用的数据访问层。
我知道可以使用连接上可用的工厂方法创建 DbCommand
。
objDbCon.CreateCommand();
但是,我找不到任何东西来创建DbDataAdapter
。这是 ADO.NET 中的错误还是什么?
I want to create a data access layer that works with any data provider.
I know it's possible to create a DbCommand
using the factory method available on the connection.
objDbCon.CreateCommand();
However, I could not find anything to create a DbDataAdapter
. Is this is a bug in ADO.NET or what?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
从.NET 4.5开始,在编写独立于提供程序的代码时,您现在可以使用
DbProviderFactories.GetFactory
重载接受DbConnection
获取正确的提供程序工厂,然后您可以从中创建数据适配器。示例:
似乎 ADO.NET 团队中的某个人阅读了 Ian Boyd 对他的答案的评论...:)
As of .NET 4.5, when writing provider independent code, you can now use the
DbProviderFactories.GetFactory
overload that accepts aDbConnection
to obtain the correct provider factory from which you can then create a data adapter.Example:
It seems someone on the ADO.NET team read Ian Boyd comment on his answer... :)
DbProviderFactory.CreateDataAdapter *
您也可以通过 DbProviderFactories 类获取所有已注册的 DbProvider 。
*我认为这个方法有一个错误的地方。
DbProviderFactory.CreateDataAdapter *
Also you can get all registered DbProviders via DbProviderFactories class.
*I think this is a wrong place for this method.
虽然 Sergey 很好地回答了这个问题,但我花了一些时间才将其转化为我自己的需求。所以我的理解是,如果您有 DbConnection 但知道您在幕后使用 SqlClient,您的代码将类似于:
Although this was answered well by Sergey, it took me a little while to translate it to my own needs. So my understanding was that if you had a DbConnection but knew you were using a SqlClient under the hood your code would look something like:
您可以使用另一种方式将数据获取到 DataTable 中,而无需使用 DbDataAdapter。
这是我的代码
You can use another way to get data into DataTable without DbDataAdapter.
Here is my code
鉴于您不知道给定的连接类型,.NET 没有提供解决该问题的好方法。这是我们使用的:
Given that you don't know the type of connection you are given, .NET provides no good way to solve the problem. Here's what we use:
死灵术。
如果您低于 .NET 4.5,则可以通过与已编译的 Linq-Expression 的连接从受保护的属性 DbProviderFactory 获取它:
Necromancing.
If you're below .NET 4.5, then you can get it from the protected property DbProviderFactory from the connection with a compiled Linq-Expression: