System.InvalidOperationException:ConnectionString属性尚未初始化

时间:2018-10-16 14:46:51

标签: c# sql sqlconnection

我浏览了有关此主题的几个答案,但没有找到关于此错误的充分答案。我在另一个课程中有一个非常相似的设置,并且那里没有问题,但是由于某种原因,这是一个问题。

public partial class DishManager : Window
{
    SqlConnection sqlConnection;

    public DishManager()
    {
        InitializeComponent();
        string connectionString = ConfigurationManager.ConnectionStrings["POS_WPF1.Properties.Settings.POSdbConnectionString"].ConnectionString;
        sqlConnection = new SqlConnection(connectionString);
    }

    private void AddDish_Button(object sender, RoutedEventArgs e)
    {
        try
        {
            string query = "if not exists (select * from Dish where Name = @Name) insert into Dish values (@DishID, @Name, @Price, @CategoryID)";
            SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);

            sqlConnection.Open();
            sqlCommand.Parameters.AddWithValue("@DishID", dishIDBox.Text);
            sqlCommand.Parameters.AddWithValue("@Name", dishNameBox.Text);
            sqlCommand.Parameters.AddWithValue("@CategoryID", categoryComboBox.SelectedIndex);
            sqlCommand.Parameters.AddWithValue("@Price", dishCostBox.Text);

            sqlCommand.ExecuteScalar();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            sqlConnection.Close();
        }
    }
}

存储的信息如下:

CREATE TABLE [dbo].[Dish] (
    [Id]         INT           IDENTITY (1, 1) NOT NULL,
    [DishID]     INT           NOT NULL,
    [Name]       NVARCHAR (50) NOT NULL,
    [Price]      MONEY         NOT NULL,
    [CategoryID] INT           NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FKCategory] FOREIGN KEY ([CategoryID]) REFERENCES [dbo].[Category] ([Id])
);

除了将类别链接到另一个表之外,情况几乎相同。

Here is a what I get when the button is pressed.

任何建议将不胜感激,并在此先感谢。

1 个答案:

答案 0 :(得分:0)

我设法通过在每个班级成员中本地初始化SqlConnection来解决此问题:

SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["POSdbConnectionString"].ConnectionString);

我有点困惑为什么在这种情况下全局声明的变量将停止工作。