正在寻找如何创建Generic CreateDataAdapter

时间:2012-04-23 04:33:34

标签: c# .net ado.net dataset dataadapter

创建数据集,例如

 System.Data.Common.DBConnection conn = getConn();
 DbCommand com = conn.CreateCommand();

 DbDataAdapter da = // get a datadapter from conn ??? There is NO CreateDataAdapter here ?
 da.SelectCommand = com;
 da.Fill(ds);

任何帮助?

更新 - 我知道那里没有CreateDataAdapter()方法,正在寻找解决方法!

4 个答案:

答案 0 :(得分:5)

新增功能,在.NET Framework 4.5中:GetFactory(DbConnection)

public static DbDataAdapter CreateDataAdapter(DbConnection connection)
{
   DbProviderFactory factory = null;
   factory = DbProviderFactories.GetFactory(connection);

   if (factory == null)
         throw new ArgumentException("Could not locate factory matching supplied DbConnection", "connection");

   return factory.CreateDataAdapter();
}

另见

  

注意:任何代码都会发布到公共域中。无需归属。

答案 1 :(得分:2)

我不确定是否理解正确..但也许你想要这样的东西:

 using (System.Data.Common.DBConnection conn = getConn())
 {
  DbCommand com = conn.CreateCommand();
  DbDataAdapter da = CreateAdapter(com);
  // .. properties of adapter ..
  da.Fill(ds);
 }

编辑(未测试):

您可以像这样创建通用的CreateAdapter方法(将根据命令类型创建适配器):

private static DbDataAdapter CreateAdapter<T>(T a_command) where T: DbCommand
{
     if (a_command is SqlCommand)
     {
        return new SqlDataAdapter();
     }

     // .. others adapters..

     return null;
}

答案 2 :(得分:1)

使用反思:

        DbConnection conn = getConn();
        string assemblyName = conn.GetType().Assembly.FullName;
        string typeName = conn.GetType().FullName.Replace("Connection", "DataAdapter"); // You may be more conservative than this
        DbDataAdapter adapter = (DbDataAdapter)Activator.CreateInstance(assemblyName, typeName).Unwrap();

答案 3 :(得分:0)

在备注部分查看here,它表示在使用DbDataAdapter时需要实现以下构造函数。

从外观上看,我认为你应该继承DbDataAdapter而不是直接使用它。尝试使用OledbDataAdapter

        OleDbConnection conn = getConn();
        OleDbCommand com = conn.CreateCommand();

        OleDbDataAdapter da = new OleDbDataAdapter(comm, conn);
        da.Fill(ds);