开发者

Reading data returned from stored procedure

开发者 https://www.devze.com 2023-04-01 08:20 出处:网络
I have a stored procedure that returns a table (or dataset or view or whatever it\'s called, it returns the result of a select). I use entity framework and I\'d expect it to treat the stored proc like

I have a stored procedure that returns a table (or dataset or view or whatever it's called, it returns the result of a select). I use entity framework and I'd expect it to treat the stored proc like a table by creating an entity. When I add the proc to the entity schema, it's added but no class is generated (nothing appears on the schema or in the intellisense).

I do not want to use this dataset solution that looks ugly and unoptimised:

SqlCommand sqlCommand = new SqlCommand("sp_ProjetsVoxco");
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Connection = new SqlConnection(
    Settings.Default.ConnectionStrin开发者_如何学JAVAgTransit);
SqlDataAdapter sa = new SqlDataAdapter(sqlCommand);
DataSet dataSet = new DataSet();
sa.Fill(dataSet);

I've found a line that seems to be very neat:

var x = context.ExecuteStoreQuery<T>("sp_ProjetsVoxco");

But since entity framework did not generate a class, I'm not really sure what to do with the T.


Adding stored procedure to the model is not enough. You must also add function import. Function import is mapping of the stored procedure to method in your context (the method should be generated for you). In this mapping you can either map result to existing entity, complex type or define a new complex type.

ExecuteStoreQuery has nothing to do with imported stored procedure. It is used to execute SQL directly (= mostly avoiding EF) and T must be your custom type which has public settable properties with same names as result set returned from your stored procedure.


I'll assume that you have your edmx file and you are now trying to add a Store Procedure that you already have created in the Database.

1 - You should add your Store Procedure that by adding it just like any other table using the Update Model from database option, this will make EF to know about a SP. (Because I already have my SP I'm showing the Refresh tab, but you will see your SP's in Add tab if you didn't add them yet)

Reading data returned from stored procedure

2 - Import a function

Reading data returned from stored procedure

3 - Give it a name and create a new Complex Type

Reading data returned from stored procedure

4 - Click OK and use the new method name

public IEnumerable<mySPMethodCallName_Result> ListAllServiceLogsFromSP(decimal clientId)
{
    var r = from sp in db.sp_ListServiceLogsByClientId(clientId)
            select sp;

    return r;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消