ASP .NET MVC 3模型+存储过程

fge*_*iew 5 .net c# stored-procedures models asp.net-mvc-3

我是ASP MVC的新手,我不知道如何根据我的数据库中的存储过程创建模型.我已经有了与其他应用程序一起工作的数据库,我的网页必须使用提到的数据库.

如果有人可以向我展示一些描述如何做到这一点的正确方法的代码,我将不胜感激.(如果我不清楚:我需要创建使用我的数据库中的存储过程的ASP .NET模型,仅此而已)

txh提前

小智 6

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)