Answered Mapping a sproc that returns a scalar value

  • Saturday, April 24, 2010 1:30 PM
     
     

    When I use "Create Function Import" in EF4 to map a sproc that returns a bigint, I get a function that returns an ObjectResult<long?>, although the Column Information displays "nullable - false". Why does it make the result nullable, and is there any way to get just an ObjectResult<long>? (Actually it's just a single long that I want, not a collection of longs, but that seems to be impossible in the Entity Framework, although in Linq to SQL it was simple.)

Answers

All Replies

  • Sunday, April 25, 2010 1:45 PM
     
     
    Can we see the sproc code?  Then I can try to reproduce it.
  • Sunday, April 25, 2010 3:56 PM
     
      Has Code

    Sure. The sproc retrieves the row count for the specified table from DMVs.

    CREATE PROCEDURE [dbo].[GetRowCount] 
    (
    	@tableName nvarchar(100)
    )
    AS
    		select row_count
    		 from sys.dm_db_partition_stats d, sys.objects o
    		 where d.index_id < 2 and o.name = @tableName and d.object_id = o.object_id
    GO
  • Sunday, April 25, 2010 7:04 PM
     
     Answered

    Yes totally...Same thing here.  However, I believe it is the expected behavior.  See this link

    http://www.danrigsby.com/blog/index.php/2009/05/20/entity-framework-40-scalar-and-void-functions/

    Two things come to mind.

    1 you could just get the count property of the entitycollection that is represented by the table context.MyEntitiySet.Count()

    2. You could do as the link suggests

    ObjectResult<int?> result = context.GetRowCount("MyTableName");
    int ret = result.FirstOrDefault().Value.ToString();

    Or even shorter

     int ret = context.GetRowCount("MyTableName").FirstOrDefault().Value.ToString();

     

    Neither are awesome though

     

     

     

  • Sunday, April 25, 2010 8:49 PM
     
     
    Thank you for the info. context.GetRowCount("MyTableName").First().Value is what I use currently. I don't want to use context.MyEntitiySet.Count(), because it will probably generate a "select count(*)"-type query, which I think can be too expensive with larger tables.