ASP .NET MVC 3型号+存储过程 [英] ASP .NET MVC 3 Models + stored procedures

查看:129
本文介绍了ASP .NET MVC 3型号+存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林,新的ASP MVC,我不知道如何创建它的型号基础上,从我的数据库存储过程。我已经数据库,与其他应用程序的工作,和我的网页必须使用上述分贝。

Im, new in ASP MVC and I don't know how to create Models which base on stored procedures from my db. I have already database which works with another application, and my web page must use mentioned db.

我会gratefull如果有人能告诉我一些片code描述的正确方法如何做到这一点。 (如果我不是清楚:我需要创建一个使用存储过程从我的数据库,并没有更多的ASP.NET模型)

I would be gratefull if someone can show me some piece of code describing the proper way how to do that. (if I wasnt clear: I need to create ASP .NET Models which use stored procedures from my database and nothing more)

TXH提前

推荐答案

@fgeorgiew你只是需要知道如何从一个存储过程填充模型(类)?你可以使用像NHibernate的或实体框架的ORM处理管道给你,或者只是使用原始的ADO.NET code,就像在下面的例子。请注意,这只是粗略的code,但你的想法。

@fgeorgiew are you just needing to know how to populate a model (class) from a stored procedure? You could use an ORM like NHibernate or Entity Framework to handle the plumbing for you, or just use raw ADO.NET code, like in the example below. Note, this is just rough code, but you get the idea.

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;
    }
}

这篇关于ASP .NET MVC 3型号+存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆