namespace MvcApplication1.Models { public class CustomerDataContext { List<customer> GetAllCustomerData(){ List<customer> customers = new List<customer>(); SqlConnection conn = new SqlConnection("initial catalog=northwind; integrated security=SSPI"); SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (reader.Read()) { Customer customer = new Customer(); for (int i = 0; i < reader.FieldCount; i++) { PropertyInfo property = customer.GetType().GetProperty(reader.GetName(i)); property.SetValue(customer, (reader.IsDBNull(i)) ? "[NULL]" : reader.GetValue(i), null); } customers.Add(customer); } reader.Close(); return customers;} } }
Controller中的寫法:
public ActionResult Customers(){ List<models.customer> customers = Models.CustomerDataContext.LoadCustomers(); return View(customers); }
參考資料:
沒有留言:
張貼留言