views:

1295

answers:

2

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.

A: 

Just a wild guess (I haven't used EF with stored procs): wouldn't the name of the function used in "ExecuteFunction" have to be the same as the stored proc's name??

return base.ExecuteFunction("MyCustomerAdd", nameParameter, surNameParameter);

ALTER procedure [dbo].[proc_MyCustomerAdd]

Can you try to use:

return base.ExecuteFunction("proc_MyCustomerAdd", nameParameter, surNameParameter);

Does that make any difference?

Marc

marc_s
i find solution. Thanks alot.
Phsika
You can change sp name in C# " proc_MyCustomerAdd--->MyCustomerAdd"
Phsika
Yes, you can change the name of the procedure in C# - but the stored proc is still called "proc_MyCustomerAdd", and when calling base.ExecuteFunction, I understand you have to give it the name of the stored procedure - no matter what your C# function is called....
marc_s
A: 
  try
            {
                enttiyContext.MyCustomerAdd(textName.Text.Trim(), textSurName.Text.Trim()); // sp Çalıştırıyorum.
            }
            catch (Exception ex)
            {

                ;
            }
            finally
            {
                ;
            }

Added Process runs correctly. On the other hand ; after added process, give Above error.But My solution run correct!!!

Phsika
Just a question..But is there a way to do this without try/catch?
Luke101