我有一个简单的应用程序,它从数据库中读取以设置类中的属性,然后将结果集输出到屏幕以及写入文件。我正在尝试提前计划我的应用程序是一个 Web 应用程序,并希望它的设计尽可能接近最佳实践。我想知道我的 DAL 设计是否有任何重大缺陷,以及我从用户那里获取输入并将其设置为参数的方式是否正常,或者是否有更好的方法。程序中的所有内容都按预期工作。
达尔
public static List<Customers> GetCustomersByName()
{
//make the list of the type that the method will be returning
List<Customers> c = new List<Customers>();
//make a connection string variable
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
using(SqlCommand cmd = new SqlCommand("spFindCustomersByName",con))
{
con.Open();
//this stored procedure has one input parameter, how do I send that to the data access layer?
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@lastName", SqlDbType.VarChar, 50);
//only way I could think of to get the value entered from a screen into
//a parameter
cmd.Parameters["@lastName"].Value = Customers.AddSpParams();
//instantiate SqlDataReader
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
Customers custList = new Customers();
custList.CustomerId = Convert.ToInt32(rdr["customerId"]);
custList.LastName = rdr["lastName"].ToString();
custList.FirstName = rdr["firstName"].ToString();
custList.DateHired = (DateTime)rdr["dateHired"];
c.Add(custList);
}
}
return c;
}
为存储过程的输入参数赋值的方法
public static string AddSpParams()
{
Console.Write("Search for a string in customer's name: ");
string nameParam = Console.ReadLine();
return nameParam;
}
写入文本文件,写入控制台
static void Main(string[] args)
{
Console.WriteLine("This is only a test");
List<Customers> c = DataAccessCustomers.GetCustomersByName();
using (StreamWriter sw = new StreamWriter(@"C:\Users\customersList.txt"))
{
foreach(Customers custList in c)
{
//write to console
Console.WriteLine(custList.CustomerId + "\t" + custList.FirstName + "\t" +
custList.LastName + "\t" + custList.DateHired);
//write to file
sw.WriteLine(custList.CustomerId + "\t" + custList.FirstName + "\t" +
custList.LastName + "\t" + custList.DateHired);
}
}
Console.ReadLine();
}