我試圖在我的asp.net mvc 5應用程序中實現NLayering,並將應用程序分成不同的層,其中一個是數據訪問層(DAL)。在我的DAL中,當我試圖在我的Insert方法中訪問連接字符串時,我得到一個NullReferenceException。我已將System.Configuration引用添加到我的DAL項目和包含ff代碼的web.config文件。嘗試從web.config獲取連接字符串時引發NullReferenceException
的web.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="JcSpaceConnectionString" connectionString="Data Source=localhost;Initial Catalog=JcSpaceDatabase;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
JcSpaceDAL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using JcSpaceEntities;
namespace JcSpaceDAL
{
public class JcSpaceDAL
{
public static void Insert(JcSpaceAccount accountInfo)
{
string connectionString = ConfigurationManager.ConnectionStrings["JcSpaceConnectionString"].ConnectionString;//This line causes the nullreferenceexception
SqlConnection conn;
SqlCommand cmd;
using (conn = new SqlConnection(connectionString))
using (cmd = new SqlCommand("spInsert")) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name", accountInfo.FirstName.ToString()+""+ accountInfo.LastName.ToString());
cmd.Parameters.AddWithValue("@Email", accountInfo.Email);
cmd.Parameters.AddWithValue("@DateOfBirth", acco untInfo.DateOfBirth);
cmd.ExecuteNonQuery();
}
}
}
}
它爲什麼會造成這個?
您需要在您的mvc項目web.config中具有相同的連接字符串部分 – Damith
您應該**調試/添加日誌**。 –