在Linq中使用sql server存储过程我在会话对象中存储问题列表,如下所示。
DataClassesDataContext myContext = new DataClassesDataContext();
var QuestionList = myContext.sp_GetAllQuestions().ToList();
Session["QuestionsList"] = QuestionList;
如何从此会话对象中读取或转换值,如
var QuestionList= Session["QuestionsList"]
Sql存储过程看起来像这样
SELECT top 24 ROW_NUMBER() OVER (ORDER BY QuestionID) AS QuestionNo,Q.QuestionID,Q.Question,Q.Choices,Q.CorrectAnswer,
Q.RelatedInfo,Q.QuestionType,CS.Section FROM Questions Q left join dbo.ChapterSection CS on Q.SectionID=CS.SectionID
答案 0 :(得分:3)
我不是周类型会话的粉丝,因为需要键入强制转换每次使用,所以我将所有类型/对象包装在强类型会话包装中。
包装基地:
public abstract class SessionBase<T> : SessionBase where T : new()
{
private static readonly Object _padlock = new Object();
private static string Key
{
get { return typeof(SessionBase<T>).FullName; }
}
public static T Current
{
get
{
var instance = HttpContext.Current.Session[Key] as T;
if (instance == null)
{
lock (SessionBase<T>._padlock)
{
if (instance == null)
{
HttpContext.Current.Session[Key] = instance = new T();
}
}
}
return instance;
}
}
public static void Clear()
{
var instance = HttpContext.Current.Session[Key] as T;
if (instance != null)
{
lock (SessionBase<T>._padlock)
{
HttpContext.Current.Session[Key] = null;
}
}
}
}
现在创建一个对象(将其标记为可序列化帮助)
[Serializable]
public QuestionCollection
{
public QuestionCollection()
{
this.Questions = new List<Question>();
}
public List<Question> Questions { get; set; }
}
现在使QuestionCollection成为强类型的QuestionCollectionSession
public QuestionCollectionSession : SessionBase<QuestionCollection>
{
}
现在您可以使用它:
QuestionCollectionSession.Current.Questions.Add("Are you there?");
如果要从会话中清除/删除它:
QuestionCollectionSession.Clear();
答案 1 :(得分:2)
这是使用var
来推断类型的地方。
明确说明QuestionList
的类型,如下所示:
List<sp_GetAllQuestionsResult> QuestionList = = myContext.sp_GetAllQuestions().ToList();
Session["QuestionsList"] = QuestionList;
现在显而易见的是,当您从Session
获取所需的值时,您需要将其投射到这个值,如下所示:
List<sp_GetAllQuestionsResult> QuestionList= Session["QuestionsList"] as List<sp_GetAllQuestionsResult>;
// Check if the list is null or not
if(QuestionList != null)
{
// Safe to use list because it was found and successfully cast
}
答案 2 :(得分:1)
List<Question> QuestionList= Session["QuestionsList"] as List<Question>;
List<Question> QuestionList= (List<Question>) Session["QuestionsList"];
您必须具有相同类型的对象才能进行强制转换,并且必须可序列化。
如果第一个选项无法转换,第一个会给你null,第二个选项会崩溃。
答案 3 :(得分:0)
真的取决于您的QuestionsList
代表什么类型,但如果您认为QuestionList
是List<Question>
,那么您需要以下内容:
var QuestionList= Session["QuestionsList"] as List<Question>;
答案 4 :(得分:0)
News newsList=new News();
Session["news"]=newsList;
当你想获得会话对象时;
News newList=Session["news"] as News;
你必须投射会话。就像那样