ASP .NET MVC 3模型+存储过程
我是ASP MVC中的新手,我不知道如何根据我的db中的存储过程创建模型。 我已经有数据库与另一个应用程序一起工作,我的网页必须使用提到的数据库。
如果有人可以向我展示一些描述如何做到这一点的正确方法的代码,我将不胜感激。 (如果我不清楚:我需要创建使用我的数据库中的存储过程的ASP .NET模型,仅此而已)
txh提前
@fgeorgiew你只需要知道如何从存储过程填充模型(类)? 您可以使用像NHibernate或Entity Framework这样的ORM来为您处理管道,或者只使用原始ADO.NET代码,如下例所示。 请注意,这只是粗略的代码,但你明白了。
public class MyModel { public int ModelId { get; set; } public string FirstName { get; set; } } public class SqlMyModelRespoitory : IMyModelRepository // optional for DI/IoC, assume interface with GetSingleModel method { public MyModel GetSingleModel() { MyModel model; string connString = "server=10.1.1.1;database=MyDb;uid=me;pwd=hidden"; using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "p_GetMyModelFromDb"; using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { model = new MyModel { ModelId = Convert.ToInt32(reader[0]), FirstName = reader[1].ToString() }; } } } } return model; } }
您可以从一些抽象开始,表明您的意图:
public interface IMyRepository { SomeModel Get(int id); }
然后你可以编写一个将使用你的存储过程的实现:
public class MyRepositorySql: IMyRepository { public SomeModel Get(int id) { ... call your stored procedure } }
然后设计你的控制器,以便它将这个抽象作为参数:
public class MyController: Controller { private readonly IMyRepository _repository; public MyController(IMyRepository repository) { _repository = repository; } public ActionResult Index(int id) { var model = _repository.Get(id); return View(model); } }
现在剩下的就是配置你的DI框架,将正确的实现传递给控制器的构造函数。 正如您现在所看到的,控制器与获取数据的方式完全分离。 无论您是在数据访问层中使用StoredProcs,某些ORM还是其他任何内容,都无关紧要。
如何在Asp.Net MVC中调用存储过程
using System; using System.Collections.Generic; using System.IO; using System.Data; using System.Data.Entity; using System.Net; using System.Data.SqlClient; public partial class StudentRecord { public int Id { get; set; } public string Name { get; set; } public string Marks { get; set; } public string Grade { get; set; } public Nullable DOB { get; set; } } public class SqlMyModelRespoitory : First_Test_DBEntities { public StudentRecord GetSingleModel() { StudentRecord model; string connString = @"Paste Your Local Connection String"; using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "InsertStudent"; using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { model = new StudentRecord { Id = Convert.ToInt32(reader[0]), Name = reader[1].ToString(), Marks = reader[1].ToString(), Grade = reader[1].ToString(), DOB = Convert.ToDateTime(reader[1]) }; } } } } return model; } }
好吧,假设您有一个名为Customers的SP,它正在选择一些列,如:
ID
名称
地址
现在,您将在Model文件夹中创建一个名为“Customer.cs”的Model类,并定义如下属性:
public int ID { get; set; } public string Name { get; set; } public string Address { get; set; }
这是你的MODEL课程。