Defining function in one class and calling in othe

2019-08-30 01:45发布

I have defined the function in one class like

public static DataSet GetAllPrimaryKeyTables()
{
  //An instance of the connection string is created to manage the contents of the connection string.
  using(var sConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]))
  {
    //To Open the connection.
    sConnection.Open();

    //Query to select the table_names that have PRIMARY_KEYS.
    string selectPrimaryKeys = @"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                                 WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME <> 'dtProperties'
                                 ORDER BY TABLE_NAME";

    //Create the command object
    using(var sCommand = new SqlCommand(selectPrimaryKeys, sConnection))
    {
      try
      {
        //Create the dataset.
        DataSet dsPrimaryKeyTables = new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS ");

        //Create the dataadapter object.
        SqlDataAdapter daPrimaryKeyTables = new SqlDataAdapter(selectPrimaryKeys, sConnection);

        //Provides the master mapping between the sourcr table and system.data.datatable
        daPrimaryKeyTables.TableMappings.Add("Table", "INFORMATION_SCHEMA.TABLE_CONSTRAINTS ");

        //Fill the dataadapter.
        daPrimaryKeyTables.Fill(dsPrimaryKeyTables);

        //Bind the result combobox with non primary key table names
        DataViewManager dsvPrimaryKeyTables = dsPrimaryKeyTables.DefaultViewManager;

        return dsPrimaryKeyTables;
      }
      catch(Exception ex)
      {
        //Handles the exception and log that to the EventLog with the original message.
        EventLog log = new EventLog("Application");
        log.Source = "MFDBAnalyser";
        log.WriteEntry(ex.Message);

        return null;
      }
      finally
      {
        //checks whether the connection is still open.
        if(sConnection.State != ConnectionState.Closed)
        {
          sConnection.Close();
        }
      }
    }
  }
}

And now how should i code so that I can call that function in another class in a dafault dataset.

Will anybody please help me??

2条回答
\"骚年 ilove
2楼-- · 2019-08-30 02:37

Making this function an Extension Method on DataSet type will sole your problem if I understand you,

查看更多
我只想做你的唯一
3楼-- · 2019-08-30 02:37

You will use something like this.

Dataset myPrimaryKeyDataset = YourClassName.GetAllPrimaryKeyTables();

Hope this helps.

查看更多
登录 后发表回答