Question

I have the following problem

I have a stored procedure that does some complex processing and in the end needs to select the distinct rows

Something like this

Create Procedure MyProc
    @par1 as nvarchar(50)
As
    select fld1, fld2 into #tmpTable from Table1
    union
    select fld1, fld2 from Table2
    union
    select fld1, fld2 from Table3

    -- select result
    select distinct fld1, fld2 from #tmpTable

I need to call this stored procedure from EF. I added it to ED model, but EF generated no result complex type.

I don't want to manually create a complex type in the model, because the actual stored procedure is complex, and if over time the stored procedure might change (by adding / altering result columns), I will have to manually edit the complex type also (which I want to avoid)

The example shown above is trivial, the real stored procedure returns much more columns, from a very complex query (about 6-10 tables with multiple joins). And having to manually maintain the associated complex type looks to me like a maintenance nightmare.

This is what I want to avoid, and to have the possible errors caught as soon as possible.

Thanks

Was it helpful?

Solution 2

Currently, I'm using the following approach:

  1. I created a view that returns no row with the exact structure as the stored procedure result - View1
  2. in the stored procedure, I include Union Select from View1
  3. in EF, I added the View1 to model (to create entity from it) and map that entity to the result of the stored procedure

Here is the code:

Create View View1 as 
    select cast('' as nvarchar(20)) as fld1,  cast(0 as int) as fld2 

Create Procedure MyProc
    @par1 as nvarchar(50)
As
    select fld1, fld2 into #tmpTable from Table1
    union
    select fld1, fld2 from Table2
    union
    select fld1, fld2 from Table3
    union
    select fld1, fld2 from View1

    -- select result
    select distinct fld1, fld2 from #tmpTable

With this approach, I accomplish what I need:

  • the stored procedure in EF returns a complex type, which gets updated when I update the model from DB
  • the stored procedure and the complex result type don't get off-sync; that's because if by any chance the stored procedure gets changed, to return a different result set, and the related view is not updated accordingly, this will get caught as soon as the stored procedure is tested - because of the union join.

OTHER TIPS

Create a separate program which reads the stored procedure, reads values from it then generates the source code you were considering to write manually. After the code is generated, the program should rebuild the project/solution, so, you will only have to run this new program to re-generate the code and build the project/solution when you change the source code of the stored procedure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top