下面是我的ASP.NET MVC项目的模型类。 我担心下面的代码。当多个用户使用静态函数时,使用静态函数返回网站列表是一个好主意吗? 当用户通过静态函数访问数据时是否会发生冲突?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BusinessLogic;
using System.Configuration;
using System.Data;
namespace Exam.Models
{
public class QuestionGroups
{
public int GroupID { get; set; }
public DateTime CreatedDate { get; set; }
public string GroupTitle { get; set; }
public string PreviewText { get; set; }
public string Keywords { get; set; }
public int ExamID { get; set; }
public string ExamName { get; set; }
public static List<QuestionGroups> GetQuestionGroupList ()
{
List<QuestionGroups> questionGroupList = new List<QuestionGroups>();
string constr = ConfigurationManager.ConnectionStrings["ExamConstr"].ConnectionString;
string sqlQuery = "SELECT A.*, B.ExamName FROM QuestionGroups A INNER JOIN Exams B ON A.ExamID = B.ExamID";
DataLayer dl = new DataLayer(constr);
DataTable tableData = dl.GetRows(sqlQuery, null);
foreach(DataRow singleRow in tableData.Rows)
{
QuestionGroups qgroup = new QuestionGroups();
qgroup.GroupID = Convert.ToInt32(singleRow["GroupID"]) ;
qgroup.CreatedDate = Convert.ToDateTime(singleRow["CreatedDate"]);
qgroup.GroupTitle = singleRow["GroupTitle"].ToString();
qgroup.PreviewText = singleRow["PreviewText"].ToString();
qgroup.Keywords = singleRow["Keywords"].ToString();
qgroup.ExamID = Convert.ToInt32(singleRow["ExamID"]);
qgroup.ExamName = singleRow["ExamName"].ToString();
questionGroupList.Add(qgroup);
}
return questionGroupList;
}
}
}
以下是我的DataLayer类的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace BusinessLogic
{
public class DataLayer
{
string connectionString = "";
public DataLayer(string constr)
{
connectionString = constr;
}
public DataTable GetRows(string sqlQuery, SqlParameter[] sqlParam)
{
DataTable tableData = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand com = new SqlCommand(sqlQuery, con))
{
com.Parameters.AddRange(sqlParam);
con.Open();
SqlDataReader dread = com.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(dread);
dread.Close();
}
}
return tableData;
}
}
}
答案 0 :(得分:3)
静态函数很好 - 它们只是让你在没有包含类的实例的情况下调用函数。
静态数据对于ASP.NET站点来说非常糟糕,因为静态数据将在所有会话中共享。
也就是说,由于您没有使用任何静态数据,因此该方法没有理由成为static
。我想说你需要将“获取数据”功能从数据类本身分离到“存储库”类等,并使用非静态方法。