简体   繁体   English

从Linq中的存储过程返回对象

[英]Return object from Stored procedure in Linq

I have a linq expression that i need to change to an Stored procedure. 我有一个linq表达式,我需要更改为存储过程。 This linq expression returns a defined object from the dbml (a table). 此linq表达式从dbml(表)返回定义的对象。

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. 事实是,当我调用存储过程(比如说SP_test)时,它返回一个SP_testResult数组,而我希望它返回一个已定义的表作为对象。

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. 如果我在dbml中更改了SP的返回类型,则当我检查结果时,它不会返回任何内容,但是如果我自己运行SP,它将返回一个集合。

Is there a way to define the type of return? 有没有定义退货类型的方法? say that SP_test returns a Client object? 说SP_test返回一个Client对象? (that is a table in my dbml model) or should i map the SP_testResult into a Client object? (这是我的dbml模型中的表),还是应该将SP_testResult映射到Client对象?

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. 在这两种情况下,this.bookings都是Bookings类的一个数组。

Perhaps consider doing something like this to map your SP results to your custom object: 也许考虑做这样的事情将您的SP结果映射到您的自定义对象:

//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.
        }
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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