EF has been used in recent projects. Although EF is similar To Linq To SQL, EF (version 3.5 and Version 4.0 are not noticed yet) is not easy enough.
Take the Stored Procedure for example. EF can call the stored procedure instead of directly dragging it in the database. We also need to perform a function import step to create a ing. If your stored procedure returns a select * from... statement, congratulations, your stored procedure can be used directly. But what if your stored procedure returns a scalar value? No, you will find that the name of the stored procedure is not displayed in your code prompt.
Why? The reason is that EF does not automatically generate cs code for the stored procedure that returns the scalar value. It only writes such
<Function Name = "GetOrder" Aggregate = "false" BuiltIn = "false" NiladicFunction = "false" IsComposable = "false" ParameterTypeSemantics = "AllowImplicitConversion" Schema = "dbo">
<Parameter Name = "OrderID" Type = "int" Mode = "In"/>
</Function>
Such a string of ing configurations. If you need to call this stored procedure in EF, you must write a general call method. The following is the method code:
Private T ExecuteFunction <T> (string functionName, System. Data. EntityClient. EntityParameter [] parameters) where T: struct
{
System. Data. EntityClient. EntityCommand cmd = (System. Data. EntityClient. EntityConnection) this. Connection). CreateCommand ();
Cmd. CommandType = System. Data. CommandType. StoredProcedure;
Cmd. Parameters. AddRange (parameters );
Cmd. CommandText = this. DefaultContainerName + "." + functionName;
Try
{
If (cmd. Connection. State! = System. Data. ConnectionState. Open)
Cmd. Connection. Open ();
Var obj = cmd. ExecuteScalar ();
Return (T) obj;
}
Catch (System. Exception)
{
Throw;
}
Finally
{
Cmd. Connection. Close ();
}
}
Generic T is the type of your Stored Procedure return value.
Although you have called a method, you cannot relax. Note that there is such a var obj = cmd in the method. executeScalar (); is the first row of data in the returned table returned? The problem is that he can only get the return value in the form of table. If your stored procedure uses return to return the result, I am sorry, the above method will throw the data reader returned by the store data provider does not have enough columns for The query requested. because the return stored procedure does not return a table. In this case, we have to modify the stored procedure and change return to select, so that the call can be successful.