簡體   English   中英

如何使用Entity Framework 6從存儲過程中獲取額外的列值?

[英]How to Get Extra Column Value From Stored Procedure using Entity Framework 6?

基本上我正在使用NopCommerce 3.2 我已經修改了存儲過程,因此它可以返回與Prodcut詳細信息關聯的CategoryName ,例如;

--return products
    SELECT TOP (@RowsToReturn)
        p.*, c.Name as CategoryName
    FROM
        #PageIndex [pi]
        INNER JOIN Product p with (NOLOCK) on p.Id = [pi].[ProductId]
        -- Custom INNER JOIN To Get CategoryName
        INNER JOIN Product_Category_Mapping pc ON pc.ProductId  = p.Id
        INNER JOIN Category c ON c.Id = pc.CategoryId
    WHERE
        [pi].IndexId > @PageLowerBound AND 
        [pi].IndexId < @PageUpperBound
    ORDER BY
        [pi].IndexId

如您所見, ResultSet檢索了CategoryName 在此處輸入圖片說明
在我的代碼中,我創建了一個帶有ignor映射的自定義屬性;

// Product.cs
public string CategoryName { get; set; }
// another mapping class i.e ProductMapp.cs
this.Ignore(p => p.CategoryName);

使用此代碼(最小化)檢索實際的ResultSet

        // some parameters sent by nopcommerce
        var pTotalRecords = _dataProvider.GetParameter();
        pTotalRecords.ParameterName = "TotalRecords";
        pTotalRecords.Direction = ParameterDirection.Output;
        pTotalRecords.DbType = DbType.Int32;
        .........
        //invoke stored procedure
        var products = _dbContext.ExecuteStoredProcedureList<Product>(
            "ProductLoadAllPaged",
            .............
            .............
            pTotalRecords);

方法(ExecuteStoredProcedureList)的定義在這里;
注意:方法代碼太長,無法粘貼,因此我嘗試僅粘貼執行代碼和映射代碼

        //var connection = context.Connection;
        var connection = this.Database.Connection;
        //Don't close the connection after command execution


        //open the connection for use
        if (connection.State == ConnectionState.Closed)
            connection.Open();
        //create a command object
        using (var cmd = connection.CreateCommand())
        {
            //command to execute
            cmd.CommandText = commandText;
            cmd.CommandType = CommandType.StoredProcedure;

            // move parameters to command object
            if (parameters != null)
                foreach (var p in parameters)
                    cmd.Parameters.Add(p);

            //database call
            var reader = cmd.ExecuteReader();
            //return reader.DataReaderToObjectList<TEntity>();
            var result = context.Translate<TEntity>(reader).ToList();
            for (int i = 0; i < result.Count; i++)
                result[i] = AttachEntityToContext(result[i]);
            //close up the reader, we're done saving results
            reader.Close();
            return result;
        }

如您所見,它正在映射到Product實體。 但是,在我的結果集中,列不能自動映射,它始終為null。 我想將CategoryName值映射到CategoryName屬性。 我怎樣才能做到這一點?

您可以在Nop.Core使用必填字段創建另一個類,而不是通過返回產品表來返回該表。 通過在存儲過程本身中創建表並在末尾刪除,該類可以是臨時的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM