我试图将列表复制到会话,但它是空的,我尝试了下面的代码。
var questions = dbContext.Sft_Set.Where(s => s.Sft_Set_ID == currentSet)
.Select(s => new
{
id = s.Sft_Set_ID,
qid = s.Sft_QuestionID,
qName = s.Sft_Question.Q_Question,
qtype = s.Sft_Question.Q_Type
}).ToList();
Session["questionList"] = questions;
var list = Session["questionList"] as List<Sft_Set>; 发布于 2019-03-27 12:55:11
你不能这么做。
阻塞词是anonymous。您不能打开匿名类型,因为在框中没有任何已知的内容。(我没有尝试使用dynamic,但没有尝试更优雅的方法)
正如vc所说,代码应该是:
var questions = dbContext.Sft_Set.Where(s => s.Sft_Set_ID == currentSet)
.Select(s => new
Sft_Set { // <===============================
id = s.Sft_Set_ID,
qid = s.Sft_QuestionID,
qName = s.Sft_Question.Q_Question,
qtype = s.Sft_Question.Q_Type
}).ToList();
Session["questionList"] = questions;
var list = Session["questionList"] as List<Sft_Set>; 或者更有可能:
public class SomeDTOType {
public int id {get; set;}
public int qid {get; set;}
public string qname {get; set;}
public int qtype {get; set;}
}
var questions = dbContext.Sft_Set.Where(s => s.Sft_Set_ID == currentSet)
.Select(s => new
SomeDTOType { // <===============================
id = s.Sft_Set_ID,
qid = s.Sft_QuestionID,
qName = s.Sft_Question.Q_Question,
qtype = s.Sft_Question.Q_Type
}).ToList();
Session["questionList"] = questions;
var list = Session["questionList"] as List<SomeDTOType>; 发布于 2019-03-27 12:56:49
正如@ to 74在他的注释中所说的那样,list是空的,因为您已经将匿名对象的列表放入会话中,并尝试使用as关键字将这个列表转换为List<Sft_Set>对象。
因为您的匿名对象列表不能抛给List<Sft_Set>,所以您将得到null的结果。这并不意味着您的会话“questionList”为null,它只是意味着它不能被抛出。
因此,您有以下解决该问题的选项:
list为dynamic,而不使用as运算符。这意味着您不会对list进行智能感知和编译时间检查。这里是第二个选项的代码示例:
public class Question
{
public int id {get;set;} // or whatever datatype your id is
public int qid {get;set;} // or whatever datatype your qid is
public string qName {get;set;} // chose a datatype that makes sense here
public string qType {get;set;} // chose a datatype that makes sense here
}
/// .....
var questions = dbContext.Sft_Set.Where(s => s.Sft_Set_ID == currentSet)
.Select(s => new Question
{
id = s.Sft_Set_ID,
qid = s.Sft_QuestionID,
qName = s.Sft_Question.Q_Question,
qtype = s.Sft_Question.Q_Type
}).ToList();
Session["questionList"] = questions;
var list = Session["questionList"] as List<Question>; https://stackoverflow.com/questions/55377536
复制相似问题