Calling a Stored Procedure (MVC4)

2019-08-01 07:32发布

(Using MVC4 VB EF4 MSSQL Razor)

I created a Stored Procedure in the MS SQL 2008 database. Then I've added that SP into the Entity Framework model (you do not see it after opening the .edmx file, i see the SP when i open the model browser). Next i did an "Add function import..." . I did [Get Column Information] and "Create new complex type".

So now I'd like to use that SP. And using ExecuteStoreQuery seems the way to go.

The best attempt so far is this:

Function Index() As ViewResult
 Dim context As New MyEntities
 Dim Result
 ' Call the SP with parameter "A"
 Result = context.ExecuteStoreQuery(Of MySP_Result)("MySP @p0", "A").ToList
 Return View(Result)
End Function

Where "MySP_result" is the name of the Complex Type that is returned by the SP (i see it in the EF model browser). After pressing F5 i get:

The model item passed into the dictionary is of type System.Collections.Generic.List, but this dictionary requires a model item of type System.Collections.Generic.IEnumerable

So what do i have to change?

1条回答
干净又极端
2楼-- · 2019-08-01 07:50

A standard genereated list view starts with:

@ModelType Mvc4App2.[classname]

It took me a while to understand the error message correctly. you need to change that line into:

@ModelType IEnumerable(Of Mvc4App2.[name of the complex type])

I also changed the controller code a little:

Dim context As New [Name of the EF model]
Dim Result As List(Of [name of the complex type])
Result = context.ExecuteStoreQuery(Of [name of complex type])_
               ("[name of the stored procedure @p0", "[parameter 0]").ToList
Return View(Result)       
End Function       
查看更多
登录 后发表回答