我们可以在asp.net的mvc3应用程序中使用存储过程吗 [英] can we use Stored procedures in mvc3 application in asp.net

查看:59
本文介绍了我们可以在asp.net的mvc3应用程序中使用存储过程吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在ASP.NET MVC 3应用程序中使用存储过程吗? 有关示例程序的帮助.

Can we use stored procedures in a ASP.NET MVC 3 application? Help with sample programs.

推荐答案

当然,MVC和您的数据访问策略是完全不同的两件事.

这取决于您是否使用实体框架.如果是这样,则可以将过程映射到设计器中的实体模型,请在此处查看.

http://msdn.microsoft.com/en-us/data/gg699321 [ ^ ]

如果您不使用EF,那么它非常简单-它与以往完全一样.您可以只使用SqlConnection对象(或您正在使用的任何数据源)并填充数据

这是一个控制器创建存储库对象的示例,该存储库对象具有返回DataTable的方法.显然,您可以在此处拥有任何返回Domain \ Model对象或集合的内容,无论您喜欢什么.

GetOutstandingInvoices 将是您存储的过程名称.

Of course you can, MVC and your data access strategy are two completely different things.

It depends if you''re using Entity Framework or not. If you are, then you can map a procedure to an entity model within the designer, have a look here.

http://msdn.microsoft.com/en-us/data/gg699321[^]

If you''re not using EF, then it''s quite simple - it''s exactly the same as it''s always been. You can just use SqlConnection objects (or whatever datasource you are using) and populate data

Here''s an example of a controller creating a repository object which has a method that returns a DataTable. Obviously, you could have something here that returns a Domain\Model object or collection, whatever you like.

GetOutstandingInvoices would be your stored procedur name.

public class MyController : Controller
{
    private ISomeRepository _repository;
    
    public MyController()
    {
        // You'd want to use dependency injection here!
        _repository = new SomeRepository();
    }
    
    public ActionResult Index()
    {
        var data = _repository.GetOutstandingInvoices();
        return View(data);
    }

}

public interface ISomeRepository
{
    DataTable GetOutstandingInvoices();    
}

public class SomeRepository : ISomeRepository
{
    public DataTable GetOutstandingInvoices()
    {
        var results = new DataSet();

        var connectionString = ConfigurationManager
            .ConnectionStrings["MyDatabase"].ConnectionString;

        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (var command = new SqlCommand("GetOutstandingInvoices", connection))
            {
                command.CommandType = CommandType.StoredProcedure;
                
                // Add any params? 
                
                var adapter = new SqlDataAdapter(command);
                adapter.Fill(results);
            }
        }   
        
        if (results.Tables.Count > 0)
        {
            return results.Tables[0];
        }
        else
        {
            throw new ApplicationException("No data generated for invoicing");
        }         
    }
}


这篇关于我们可以在asp.net的mvc3应用程序中使用存储过程吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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