简体   繁体   中英

Return object from Stored procedure in Linq

I have a linq expression that i need to change to an Stored procedure. This linq expression returns a defined object from the dbml (a table).

The thing is that when i call my stored procedure (let's say SP_test) it return an SP_testResult array, and i want that it returns a defined table as an object.

If i change the return type of the SP in the dbml, when i check the result, it doesn't return anything, but if i run the SP by itself, it returns a set.

Is there a way to define the type of return? say that SP_test returns a Client object? (that is a table in my dbml model) or should i map the SP_testResult into a Client object?

I want to go from this:

this.bookings = db.Bookings
        .FilterUser(_main.Identity.GetUser())
        .Where(x => x.ProductId == PackageContent.ProductId && x.CampaignId == PackageContent.CampaignId && x.ClientId == PackageContent.ClientId)
        .Where(x => Math.Abs((x.DateCreated - PackageContent.DateCreated).Days) < daysRange)
        .ToList()
        .Union(db.Bookings.Where(x => PackageContent.ExternCode == x.BussinessRefernce))
        .OrderBy(x => x.DateCreated);

To this:

this.bookings = db.SP_SearchSimilarBookings.toList();

In both cases, this.bookings is an array from Bookings class.

Perhaps consider doing something like this to map your SP results to your custom object:

//create your connection string
string Conn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

using (SqlConnection connection = new SqlConnection(Conn))
{
    //add your SP to the SqlCommand
    SqlCommand cmd = new SqlCommand("dbo.MyProcedure", connection);
    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter myParam = new SqlParameter("@YourParam", //Your SqlDbType);
    myParam.Value = //your value;
    cmd.Parameters.Add(myParam);

    //Add more parameters if applicable...

    SqlDataReader dr = command.ExecuteReader();

    if (dr.HasRows)
    {
        while (dr.Read())
        {
            //map to your custom object here by instantiating one and mapping 
            //the SqlDataReader columns to your custom object properties.
        }
    }
 }

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