In ADO.NET Entity Framework, how can I start a stored procedure?

.net c# entity-framework linq-to-sql

Question

How to use stored procedure in ADO.NET Entity Framework?

My Table : MyCustomer

Columns:
CustomerID    PK   int 
Name               nvarchar(50)
SurName            nvarchar(50)

My stored procedure

ALTER procedure [dbo].[proc_MyCustomerAdd]
(@Name nvarchar(50),
@SurName nvarchar(50)
)
as 
begin
  insert into dbo.MyCustomer([Name], SurName) values(@name,@surname)
end

My C# code

private void btnSave_Click(object sender, EventArgs e)
{
   entityContext.MyCustomerAdd(textName.Text.Trim(), textSurName.Text.Trim());
   entityContext.SaveChanges();
}

The error:

The data reader is incompatible with the specified 'TestAdonetEntity2Model.MyCustomer'. A member of the type, 'CustomerID', does not have a corresponding column in the data reader with the same name.

Error occured below the last code line (call to ExecuteFunction):

global::System.Data.Objects.ObjectParameter surNameParameter;
if ((surName != null))
{
   surNameParameter = new global::System.Data.Objects.ObjectParameter("SurName", surName);
}
else
{
   surNameParameter = new global::System.Data.Objects.ObjectParameter("SurName", typeof(string));
}
<b>return base.ExecuteFunction<MyCustomer>("MyCustomerAdd", nameParameter, surNameParameter);</b>

Added is ok. Every added process is ok. But after editing, above error occurs.

1
1
6/13/2009 9:04:50 PM

Accepted Answer

I think what you need to do it a function import with the EF tooling and calling the imported function like

DataContext.MyFunctionName(storedProcedureParamer1, storedProcedureParamer2)

How to: Import a Stored Procedure

2
1/1/2014 1:20:04 PM

Popular Answer

To call Stored Procedures for query operations you can use SqlQuery in Entityframework which is very helpful

_dbContext.Database.SqlQuery<EntityType>("sp_name",parameters).ToList();

For Executenonquery Operations(Transactions) you can use

_dbContext.Database.ExecuteSqlCommand( 
                    @"UPDATE tblname SET Rating = 5" + 
                        " WHERE Name LIKE '%Entity Framework%'" 
                    );

Please note that _dbContext object of your Context class inherits from DbContext Class of Entityframework



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow