简体   繁体   中英

session object is null after update

I'm populating an object model with a linq query. The model looks like this:

MyModel{
DateTime AppointDate {get; set;}
int TotalAppoints {get; set;}
int AppointDuration {get; set;}
}

The linq-to-sql query looks like that:

    public static GetAppointsFromDB(params){

    var MyQuery = from....where...
                  select new MyModel{
                    AppointDate = ...,
                    TotalAppoints = ...,
                    AppointDuration =...};

    return MyQuery as MyModel;}

In the master page, I'm looking to load the result of this query in the session like this:

if (Session["Appoints"] == null) {Session["Appoints"] = GetAppointsFromDB(...);}

When I run with the code, the session is always null. I added this line a second time, just right after, and the query runs again. When I'm looking to use the session at some other point in the code, it is null too there too. The query works because when I put a breakpoint on the return statement, I see the object properly filled.

Please let me know where the problem comes from, I'm stuck on this seemingly simple problem and I'm not seeing what I'm doing wrong.

Thanks for your suggestions.

public static GetAppointsFromDB(params)
{

  var MyQuery = from....where...
                select new MyModel{
                AppointDate = ...,
                TotalAppoints = ...,
                AppointDuration =...};

  return MyQuery as MyModel;
}

Let's assume this method actually returns MyModel , so:

public static MyModel GetAppointsFromDB(params)

Now what you are seeing is probably that MyQuery results in something that cannot be cast to MyModel , that's why it returns null - why do you need the As operator in the first place? If your query always returns a single instance of type MyModel you should just

return MyQuery;

If your query contains an enumeration of MyModel (and this is what it looks like) and you only want to return one you could use

return myQuery.FirstOrDefault();

instead.

Most likely, it's the MasterPage.Load event is firing after the Page.Load event. Try to use the Init event of the Master Page, which will run before the Load events.

Your MyQuery variable is of type IQueryable<MyQuery> , not MyModel as you trying to cast. So this line return MyQuery as MyModel return null .

Try to change it to eg

var MyQuery = from....where...
              select new MyModel{
                  AppointDate = ...,
                  TotalAppoints = ...,
                  AppointDuration =...};

return MyQuery.ToList();

and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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