简体   繁体   中英

How to get a collection of data in Entity Framework using stored procedure

I have created a stored procedure which will return a set of data. In my case it is set of roles

CREATE PROCEDURE [dbo].[GetRoles]
@ID Int
AS
SELECT Roles.Role FROM Roles WHERE Roles.CustomerCustomerID=@customerID
RETURN 0

I am using Entity Framework to get this value to a variable like this:

var query = context.GetRoles(ID);

I am planning to manipulate this dataset and create a list of "roles" and return the list

But since I am calling the stored procedure and I am not writing the query statement here for example:

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    string LastName = "Zhou";
    var query = from contact in context.Contacts 
                where contact.LastName == LastName 
                select contact;

    // Iterate through the collection of Contact items.
    foreach( var result in query)
    {
        Console.WriteLine("Contact First Name: {0}; Last Name: {1}", 
                result.FirstName, result.LastName);
    }
}

How can I get the values that are in each result?

I can not obviously access the fields of the table in intellisense

What is the approach should I take on this issue?

Thanks In advance..

You need to create a FunctionImport in your EDMX model, and map the columns to an entity or a complex type. To do this, right click in the EDMX, choose Add/Function Import, and select the Stored Procedure from the list (if not there, refresh the model from the database). Give the FunctionImport a name (eg: "GetRoles") and choose what it returns (in your example, a collection of Scalars of whatever type Roles.Role is.

Then

var query = context.GetRoles(ID); 

will return an ObjectSet<T>, where T is the type you have mapped it to, that you can iterate through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM