Ошибка пространства имен - PullRequest
0 голосов
/ 07 декабря 2010

Я определил функцию в следующем классе, как этот

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using MFDBAnalyser;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;

namespace MFDBAnalyser
{
    public class PrimaryKeyChecker : IMFDBAnalyserPlugin
    {
        public string RunAnalysis(string ConnectionString)
        {
            return GetAllPrimaryKeyTables(ConnectionString);
        }

        /// <summary>
        /// This function populates the tables with primary keys in a datagrid dgResultView.
        /// </summary>
        /// <param name="localServer"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="selectedDatabase"></param>
        /// <returns></returns>
        public string GetAllPrimaryKeyTables(string ConnectionString)
        {
            string result = string.Empty;

            // Query to select primary key tables.
            string selectPrimaryKeyTables = @"SELECT 
                                                   TABLE_NAME
                                                  AS
                                                   TABLES
                                                FROM 
                                                   INFORMATION_SCHEMA.TABLE_CONSTRAINTS
                                               WHERE 
                                                   CONSTRAINT_TYPE = 'PRIMARY KEY'
                                                 AND
                                                   TABLE_NAME <> 'dtProperties'
                                            ORDER BY
                                                   TABLE_NAME";

            // put your SqlConnection and SqlCommand into using blocks! 
            using(SqlConnection sConnection = new SqlConnection(ConnectionString))
            using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
            {
                try
                {
                    // Create the dataadapter object 
                    SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
                    DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");

                    // Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself  
                    // (and also close it again after it is done) 
                    sDataAdapter.Fill(dtListOfPrimaryKeyTables);
                    using(StringWriter sw = new StringWriter())
                    {
                        dtListOfPrimaryKeyTables.WriteXml(sw);
                        result = sw.ToString();
                    }
                }
                catch(Exception ex)
                {
                    //All the exceptions are handled and written in the EventLog. 
                    EventLog log = new EventLog("Application");
                    log.Source = "MFDBAnalyser";
                    log.WriteEntry(ex.Message);
                }
            }

            // return the data table to the caller 
            return result;
        }
    }
}

Но когда я вызываю это так

protected void GetPrimaryKeyTables()
{
    DataTable dtPrimaryKeys = new PrimaryKeyChecker().GetAllPrimaryKeyTables(txtHost.Text, txtUsername.Text, txtPassword.Text, Convert.ToString(cmbDatabases.SelectedValue));
    dgResultView.DataSource = dtPrimaryKeys;
}

Тогда он выдает ошибки типа

Ошибка 1 Не удалось найти имя типа или пространства имен 'PrimaryKeyChecker' (отсутствует директива об использовании или ссылка на сборку?) D: \ Projects \ Mindfire \ GoalPlan \ MFDBAnalyser \ MFDBAnalyser \ MFDBAnalyser.cs 340 43 MFDBAnalyser

Ответы [ 2 ]

2 голосов
/ 07 декабря 2010

Вы не показали, какие операторы using действуют для GetPrimaryKeyTables(), но вы всегда можете использовать полное имя:

 DataTable dtPrimaryKeys = 
      new MFDBAnalyser.PrimaryKeyChecker().GetAllPrimaryKeyTables(...));

Я подозреваю, что вы допустили ошибку в одном экземпляре MFDBAnalyser

1 голос
/ 07 декабря 2010

Если класс, который определяет метод GetPrimaryKeyTables (), отсутствует в пространстве имен MFDBAnalyser, вам нужно будет включить оператор using в верхней части этого файла, например так ...

using MFDBAnalyser;

Кроме того, вы можете создать экземпляр PrimaryKeyChecker, используя его полное имя, например так ...

DataTable dtPrimaryKeys = new PrimaryKeyChecker().GetAllPrimaryKeyTables(...);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...