Saturday, September 19, 2015

Entity Framework cannot get Column Information for Complex Types result

This link saves me:

http://stackoverflow.com/questions/7128747/ef4-the-selected-stored-procedure-returns-no-columns

I have a stored procedure that joins multiple tables, performs queries and returns a Complex Types result. When setting this up in EF designer, EF cannot detect the columns returned from the stored procedure. As Ladislav pointed out, EF needs to execute the stored procedure to actually get the column information. I choose the second solution. I hack my stored procedure to include SET FTMONLY OFF. The first solution works too until someone tries to update the model from database or if the stored procedure is adjusted to return different columns.

The problem with this, well actually the problem with my stored procedure is that there's no default parameter value specified. EF executes my stored procedure with NULL parameter resulting in error as the stored procedure expects non NULL parameter value to be passed in, so I still ended up with no column information. I finally hack my stored procedure as follows:

IF @param1 IS NULL AND @param2 IS NULL
BEGIN
   SET FTMONLY OFF
   SET @param1 = 0
   SET @param2 = '1900-01-01'
END

@param1 is an identifier and @param2 is a date. Setting identifier to 0 and date to something way in the past guarantee that there's no result returned but that's okay since we're only interested in the column information.