我有一个静态类数据:
public static class Data
{
public static SqlConnection connexion;
public static bool Connect()
{
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Initial Catalog"] = "Upload";
builder["Data Source"] = "base";
builder["integrated Security"] = true;
string connexionString = builder.ConnectionString;
connexion = new SqlConnection(connexionString);
try { connexion.Open(); return true; }
catch { return false; }
}
public static void Disconnect()
{
if (connexion != null) connexion.Close();
connexion = null;
}
}
在动作 Home 中:
public ActionResult Home()
{
Data.Connect();
if (CompteModels.Connected)
{
ArrayList model = new ArrayList();
ClientModels clients = new ClientModels();
model.AddRange(clients.Client_List());
AdminModels admins = new AdminModels();
model.AddRange(admins.Admin_List());
return View(model);
}
else return RedirectToAction("Login", "Account");
}
客户端类:
public List<ClientModels> Client_List()
{
List<ClientModels> l = new List<ClientModels>();
using (Data.connexion)
{
string queryString = @"select Login, Password, Mail, Name, Tentatives from Compte where User_type_id in ( select Id from User_type where Fonction = 'Client')";
SqlCommand command = new SqlCommand(queryString, Data.connexion);
try
{
SqlDataReader reader = command.ExecuteReader();
do
{
while (reader.Read())
{
ClientModels admin = new ClientModels { Login = reader.GetString(0), Password = reader.GetString(1), Mail = reader.GetString(2), Name = reader.GetString(3), Tentatives = reader.GetInt32(4) };
l.Add(admin);
}
} while (reader.NextResult());
return l;
}
catch { return null; }
}
对于函数AdminList
,实现与Client_List
类相同Admin
。
问题出在静态变量connexion
中:在第一个函数中,Client_List
它的值是正确的,我得到了客户端列表,但它null
在第二个函数中变成了,尽管它是静态类中的静态变量!!!
这种改动的原因是什么?我该如何解决?