.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Entity Framework and stored procedures with OUTPUT parameters (suggest API)

Posted By:      Posted Date: September 07, 2010    Points: 0   Category :ASP.Net
EF does handle stored procedures with OUTPUT parameters, but the generated methods are not the easiest to work with or safest you could ask for. The ObjectParameter objects you have to create, pass to the method and extract the value from are not type checked and reallyObjectParameter nameParam = new ObjectParameter( "Name", typeof(string)); ObjectParameter ageParam = new ObjectParameter( "Age", typeof(int)); context.GetPersonsNameAndAge( personId, nameParam, ageParam); string name = Convert.IsDBNull(nameParam.Value) ? null : (string)nameParam.Value; int? age = Convert.IsDBNull(ageParam.Value) ? null : (int?)ageParam.Value; is not what I would want to have to write.The ObjectParameter objects do make some sense for stored procedures that return both a resultset and some OUTPUT parameters, because in that case the OUTPUT parameters are only available after the resultset has been consumed and therefore you need some objects that will be populated after the ObjectResult<...> gets processed but for the stored procedures that do not return any resultset, there is no reason not to create the ObjectParameter objects within the method and extract the values there as well. So that the procedure above may be called asstring name; int? age; context.GetPersonsNameAndAge( personId, out name, out age); Things are not so simple for procedures returning both. I'm

View Complete Post

More Related Resource Links

using stored procedures in ado.net entity framework model

Hi, I have a issue, i am calling stored procedure through entity model like result=ctx.spname(parmas), i am expecting 0 or 1 as a result after the execution of sp, but its returning unknown values like 178 for number records. Please suggest what went wrong Thanks

Entity Framework - stored procedure mapping, excecuting SP with float parameters separated by commas



Im using Entity framework with POCO entity generator template + SQL Server. I have mapping to stored procedure that takes two floats as input.

After executing function from code with two doubles as parameters: 1.23 and 4.56, SQL Profiler shows:

exec storedProcedureName @arg1 = 1,23, @arg2= 4,56

This is causing an error because it looks like that stored procedure takes 4 arguments, but it should take only two and there should be dots insted of commas in these floats.

My SQL Server collation is SQL_Latin1_General_CP1_CI_AS. I tried to set:

           Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
           Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

in DataContext Constructor, and di

How to call a Stored procedures with varchar output parameters in LINQ


I have a stored procedure with the following structure:

CREATE procedure EditFeriodigiesForm
@EditID int,
@producer varchar(50) output,
@IssuedDate datetime output,
@stadio varchar(50) output,
@Method varchar(50) output,
@Monades_N varchar(50) output,
@Monades_P varchar(50) output,
@Monades_K varchar(50) output,
@comments varchar(100) output,
@responsible varchar(50) output
Begin Try
	Begin tran
SELECT @IssuedDate=IssuedDate,@producer=ProducerID,@stadio=KalliergitikoStadio,@Method=Method,@Monades_N=Monades_N,@Monades_P=Monades_P,@Monades_K=Monades_K,@comments=Comments,@responsible=Responsible from ferti_odigies WHERE FertOdigiesID=@EditID
end try
	Begin catch
	if @@error>0
declare @ErrMsg varchar(4000),
		@ErrSeverity int
Select @ErrMsg=Error_Message(),

Raiserror(@ErrMsg ,@ErrSeverity,1)

end catch 

Now i need to call it in LINQ.I have done the mapping thing and the SPROC is ready to be called in my form.aspx.cs form, as following:
  int id = Edit_id;
            int? producer;
            DateTime date =Convert.ToDateTime(txtdate.Text);
            string stadio;
            string method="";
            string monadesn="";
            string monadesp="";
            string mo

Input and output parameters for stored procedures in VB.NET


I have several VB.NET functions which pass and receive values from executed stored procedures using parameters. However, the latest method I am using seems to be a little too specific on the datatype and data length of the parameters for my liking (i.e. LogActivityCommand.Parameters.Add("@strErrSource", SqlDbType.NVarChar, 300).Value = strErrSource). For example:

Public Function LogError(ByVal strErrSource As String, ByVal strErrCode As String, ByVal strErrDesc As String) As String  
    Dim AerialConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("aerialConnectionString").ConnectionString)  
    Dim RetVal As SqlParameter  
        Dim LogActivityCommand = New SqlCommand("spLogError", AerialConnection)  
        LogActivityCommand.CommandType = CommandType.StoredProcedure  
        'Add input parameters  
        LogActivityCommand.Parameters.Add("@strErrSource", SqlDbType.NVarChar, 300).Value = strErrSource &

Never SELECT * from Entity Framework called Stored Procedures


The Entity Framework can help us create an efficient Data Access Layer or a horribly inefficient one. 

It's worth mentioning that if we use Entity Framework to call a stored procedure that returns a database derived Entity using a SELECT * (star), we will have that horribly inefficient DAL.  Of course, as we've been told for years, SELECT * is 99.0% wrong with 1% for those dynamic field cases.  With EF calling a stored procedure, it's really wrong.

SQL Profiler will show us that the store procedure does return all records as fast as it can, barring a badly written stored procedure or low SQL server memory.  Entity Framework unfortunately does not assume all fields have returned.  EF then calls back with the defined primary key for each record.  This means that for a stored procedure that returns 1 million rows in one connection, actually returns 2 million rows with 2 million and one database server calls / connections from the application layer.  Try it on a 3 record table sometime to see that it calls SQL Server 4 times for three rows even when we use a stored procedure.  Enterprise DBA's will complain as they should.  If there is an obscure switch to avoid this, I

Entity Framework 4.0 Dynamic Data - stored procedure


I'm using Dynamic Data and have created a custom List.aspx page.  I simply want to populate the grid with a stored procedure.  I've seen some posts about doing this with a LinqDataSource but not an EntityDataSource.  Does someone have an example or a different way of doing this?  Thanks.

Replication stored procedures not being passed parameters- default appears instead

Hi I am setting up transactional replication from Oracle to SQL Server, it is working fine for 9 tables, but for one it fails on updating and deleting with a message like this: Procedure or function 'spu_VGSM_SUBMISSION_CONTACT' expects parameter '@pkc1', which was not supplied. This is correct, in that the sp should be being passed this parameter, but when I do a trace it will show something like: exec "spd_VGSM_SUBMISSION_CONTACT" '12-3456-10','BLOGGS','S', '2010-07-01 12:43:43', 'M123456' default In other words, the old primary key values which should be being passed in are being replaced with "default". I am using the CALL syntax for the update sp. If anyone can suggest why this is I would be very grateful. This is the publication: exec sp_addpublication @publication = N'_Submission_Contact', @description = N'Transactional publication from Oracle Publisher.', @sync_method = N'concurrent_c', @retention = 0, @allow_push = N'true', @allow_pull = N'true', @allow_anonymous = N'false', @enabled_for_internet = N'false', @snapshot_in_defaultfolder = N'true', @compress_snapshot = N'false', @ftp_port = 21, @ftp_login = N'anonymous', @allow_subscription_copy = N'false', @add_to_active_directory = N'false', @repl_freq = N'continuous', @status = N'active', @independent_agent = N'true', @immediate_sync = N'

using table valued parameters for stored procedures any limitations

I am thinking of using a table valued parameter for my new stored procedure, but wonder if there are any performance implications to be aware of and is the limitation of using statistics applicable with table value parameters, i.e do they keep statistics and will this affect the judgement of query plans i.e estimated number of rows, from my experience table variables do suffer from this problem but I would like to confirm if it applies to table value parameters as well.

How to Bind Selective Columns from Stored Proc to Gridview using the entity framework


Hi Guys,

I have this entity model>> http://img840.imageshack.us/img840/306/schemaj.jpg and I would like to bind  a list  which consists of: employee's

  • emloyee_firstname(employees table) + employee_lastname(employees table)
  • employee's extension(employee_extension table)
  • deparment name(departments table)

to my gridview. I already created my stored procedure

    Concat(employees.employee_firstname," ",employees.employee_lastname) as name
    , extensions.extension_number
    , departments.department_description
    INNER JOIN employees 
        ON (employee_extensions.employee_id = employees.employee_id)
    INNER JOIN extensions 
        ON (employee_extensions.extension_id = extensions.extension_id)
    INNER JOIN departments 
        ON (employees.department_id = departments.department_id)

But my problem is, i don't know how to bind it since i don't have an entity that contains the employee's name, extension# and departments name. Do I need to create a custom class that consists of said columns? or is their a proper way to do this? I'

Issue while creating a BCS entity in visual studio for SQL stored procedures


Hi Everyone,

                  I have an issue while creating an entity in Visual studio for SQL stored procedures.I have two input parameters startdate and enddate as datetime datatypes in the stored procedures.I have added two input parameters startdate and enddate in the Readlist and ReadItem methods and created two filter descriptors startdate and enddate of "comparison" type and related these to their respective input parameters.

                 In my readlist and readitem methods I have used LINQ TO SQL query to query the SP.When I debug the program,I am receiving an error message-->remote procedure cannot be debugged.Also my parameters are not being passed to the SP.Any help is appreciated..also if any one has step by step approach,that helps me a lot.

Creating BCS entity for a SQL stored procedure that has parameters using visual studio


Hi Everyone,

                 can anyone help me in creating  BCS entity using BCDM model in visual studio using Linq to sql query for a SQL stored procedure.I am receiving remote debugging error and few other errors.Your step by step approach helps me a lot,I have been playing with this for long,but still no answer.


Thanks ,

entity framwork with stored prcedure vs entity framwork without stored procedures


I am new to entity framwork , it is really very good , but I want to know what is the differance between using entity framwork with stored procedure or without stored procedure , which one the faster and what is the benifits for using stored procedures with entity framwork

Trying to use stored procedure in Entity Framework


I have a aspx page that only has a button and a button click event.

My code behind looks like this

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommerceModel;

public partial class test : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    protected void Button1_Click(object sender, EventArgs e)
        using (CommerceEntities context = new CommerceEntities())
                UBOtest myRecord = new UBOtest
                    dataA = "Tina",
                    dataB = "Feeney"
            catch (Exception ex)

This code works fine if I have no insert stored procedure mapped to Table UBOtest in the EntityDataModel.However, when I map the stored procedure to the EntityDataModel and add UBOtestinsert I get an error that reads "An error occured while updating the entries. See the inner exception for details.">/P>

Then the innerException message is "Invalid object name 'UBOtes

Partial update with stored procedure in Entity Framework 4


How do I use a stored procedure to change one or more (but not all) fields of a entity in EF4? I have a stored procedure "ChangePassword" taking a username and and a password as parameters and a User entity containing properties for Username and Password as well as other properties. I want to be able to use this stored procedure from a function to update the password from a function in one of my repositories. How to do this?

Which jdbc version support table valued parameters to stored procedures?


Hi all,

I want to use table valued parameters in stored procedures; we have that in .NET client, so I do not want to write another version for jdbc client.

Does anyone know, which version of jdbc engine support that function?

Please give several lines of source codes.

Thanks a million,



Pass parameters into multi stored procedures



I have a code that want to call 2 stored procedures with a sqlcommand; I'm used :


        string sqlcmds = "EXEC ShowDetailsSp;EXEC ShowBannersSp;";
        cmd = new SqlCommand(sqlcmds, sqlcon);
        cmd.Parameters.AddWithValue("@Number", number);
        cmd.Parameters.AddWithValue("@Code", Code);

each stord procedure has a parameter :

@Number is for ShowDetailsSp and @Code is for ShowBannersSp, but when I run my page give error :

Procedure or function 'ShowDetailsSp' expects parameter '@Number', which was not supplied. 

Pass parameters into multi stored procedures



I have a code that want to call 2 stored procedures with a sqlcommand; I'm used :


        string sqlcmds = "EXEC ShowDetailsSp;EXEC ShowBannersSp;";
        cmd = new SqlCommand(sqlcmds, sqlcon);
        cmd.Parameters.AddWithValue("@Number", number);
        cmd.Parameters.AddWithValue("@Code", Code);

each stord procedure has a parameter :

@Number is for ShowDetailsSp and @Code is for ShowBannersSp, but when I run my page give error :

Procedure or function 'ShowDetailsSp' expects parameter '@Number', which was not supplied. 

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend