如何通过EF调用MVC中的存储过程 [英] How to call stored procedure in MVC by EF

查看:201
本文介绍了如何通过EF调用MVC中的存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在这里可以使用企业库更好地实现实体框架的良好教程注意:我正在使用存储过程,因为它们非常复杂,其中一些是超过1000行。



/ p>

解决方案

MVC在这种情况下绝对不相关。从EF中调用存储过程的方式仍然是一样的。我想你想使用存储过程而不实际使用实体和linq-to-entities(主EF功能),不是吗?一般来说,您需要:




  • EDMX文件(ado.net实体数据模型),您可以从数据库运行更新,并添加所需的所有存储过程使用。 EDMX文件还会默认生成派生的 ObjectContext 和所有实体。

  • 接下来,你必须去模型浏览器并为每个过程创建功能导入。函数import将在派生的 ObjectContext 上创建方法,这将允许您以任何其他.net方法调用存储过程。

  • 在函数期间导入您将不得不为存储过程返回的结果集创建复杂类型(可能会自动发生)。



您也不要必须使用功能导入,您可以直接执行程序通过调用或者:




  • objectContext.ExecuteSqlCommand(storedProcedureName,SqlParameters)返回记录集

  • objectContext.ExecuteStoreQuery< ResultType>(storedProcedureName,SqlParameters) ResultType 必须具有与结果集中的列名称相同的属性。它只能使用平面类型(无嵌套对象)。



使用存储过程时有一些限制:




  • 实体框架不喜欢返回动态结果集的存储过程(基于某些条件结果集具有不同的列)

  • 实体框架不支持返回多个结果集的存储过程 - EFExtensions ,但它更像ADO.NET直接执行。 li>

Where can I get good tutorial on Entity framework with Stored Procedure in MVC framework?

Is it better to use Enterprise library in this case when I have almost everything written in the stored procedure.

Note: I am using stored procedure because they are really very complex and some of them is over 1000 lines.

解决方案

MVC is in this case absolutely not related. The way how you call stored procedure from EF will be still the same. I guess you want to use stored procedures without actually using entities and linq-to-entities (main EF features), don't you? Generally you need:

  • EDMX file (ado.net entity data model) where you run update from database and add all stored procedures you want to use. EDMX file also generates derived ObjectContext and all entities by default.
  • Next you must go to Model Browser and create Function import for each procedure. Function import will create method on the derived ObjectContext which will allow you call the stored procedure as any other .net method.
  • During function import you will have to create complex type (it can happen automatically) for result set returned from stored procedure.

You also don't have to use function imports at all and you can execute procedures directly by calling either:

  • objectContext.ExecuteSqlCommand("storedProcedureName", SqlParameters) for SPs not returning record set
  • objectContext.ExecuteStoreQuery<ResultType>("storedProcedureName", SqlParameters) for SPs returning record set. ResultType must have properties with same names as columns in result set. It can work only with flat types (no nested objects).

There are some limitations when using stored procedures:

  • Entity framework doesn't like stored procedures which returns dynamic result sets (based on some condition result set has different columns)
  • Entity framework doesn't support stored procedures returning multiple result sets - there are EFExtensions which does but it is more like doing ADO.NET directly.

这篇关于如何通过EF调用MVC中的存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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