如何从mvc3中的Session对象中检索值?

时间:2012-04-20 12:49:49

标签: asp.net-mvc asp.net-mvc-3 entity-framework stored-procedures

我有mvc 3应用程序,其中在会话对象中我将所有需要的值作为参数来执行存储过程。

如果userAction更新,则执行存储过程。

public ActionResult Index(string userAction) 
{ 
   if(Session["Mappings"] != null)            
        ViewData["Message"] = "Mapping web grid"; 

    if (Session["PricingSecurities"] == null) 
        Session["PricingSecurities"] = objRepository.GetPricingSecurityID(); 
    if (Session["Cusips"] == null) 
        Session["Cusips"] = objRepository.GetCUSIP(); 

    SecurityMappingModel objModel = null; 
    mappings = (List<SecurityMappingModel>)Session["Mappings"]; 

    objModel = new SecurityMappingModel(); 


    if (userAction == "Update" ) 
    { 
        //please tell me how can i take values from Session[Mappings] and pass it to stored procedure? 
        //i'm trying this code
        //foreach (var item in Session)
        //{objModel.Cusips = (List<SelectListItem>)Session["Mappings"];
        //I did function import here (import my sp in model)using EF name            
        //ExecuteMappingsp.
        //dbContext.ExecuteMappingsp(need to pass parameter);
        //} //i know wrong code but how to fix this??
        // PLEASE HELP ME TO RETRIEVE SESSION VALUES
        return RedirectToAction("Index"); 
    } 
    objModel.PricingSecirities = (List<SelectListItem>)Session["PricingSecurities"]; 
    objModel.Cusips = (List<SelectListItem>)Session["Cusips"]; 
    ViewBag.Mappings = mappings; 
    return View(objModel); 
} 

如何从Session [Mappings]中获取值并将其传递给存储过程?

1 个答案:

答案 0 :(得分:1)

描述

Entity Framework Code First目前不支持存储过程调用。目前,唯一的方法是使用SqlCommand。 (System.Data.SqlClient命名空间)

示例

// ....
if (userAction == "Update")
{
    // Create SqlCommand with your stored procedure name and sql connectionstring
    SqlCommand cmd = new SqlCommand("dbo.StoredProcedureName", new SqlConnection("ConnectionString"));
    // set the command type to StoredProcedure
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    // Add Parameters
    cmd.Parameters.Add("@ParameterName", Session[Mappings]);
    // execute the stored procedure
    cmd.ExecuteNonQuery();

    return RedirectToAction("Index");
} 

更多信息

更新

我无法知道您的模型,如果它是代码优先,数据库优先或shema优先,因为您没有提供该信息。但也许这有帮助

foreach (var item in (List<SelectListItem>)Session["Mappings"])
{
   dbContext.ExecuteMappingsp(PassInTheParametersYouNeedFromYourItem)
}