views:

454

answers:

3

Hi,

I am working on an ASP.NET application using LinqToSQL. When the page loads I run a query and save the results into a variable... var tasks = query expression. I then save this into a session variable Session["Tasks"] = tasks...

Is it possible to cast this session object back to its original var state, so I can run methods such as Count(), Reverse() and so on?

Thanks

+4  A: 

var is not a type, it just tells C# you figure out the type.

string s = "Hello world!";

and

var s = "Hello world!";

are equivalent and give back the same s. You are probably missing

using System.Linq

or some other that adds the extension methods you are looking for.

J. Pablo Fernández
The methods I am looking for are there, the problem is casting back to the original var during a callback. You can do (String)Session["task"]... but as far as am aware you cant do (var)Session["task"].
Chalkey
+13  A: 

var is just short-hand for type inference... the real question here is: what is the underlying type?

If it involves an anonymous type (i.e. new {...}, or a List<> there-of), then there is no elegant way (although it can be done in a hacky way). In short; don't use anonymous types in this scenario...

Note that a query expression such as IQueryable<T> is not data - it is a query - to store the data (for a cache) you'd need to use .ToList() / .ToArray() etc.

Important: you shouldn't store a query expression in session; at best (in-memory session provider) that will keep the data-context alive; at worst (database etc session provider) it won't work, as a data-context isn't serializable. Storing results from a query is fine; but otherwise, rebuild the query expression per-request.

In which case, you might be able to use (for example):

var tasksQuery = from task in ctx.Tasks
             where task.IsActive
             orderby task.Created
             select task; // this is IQueryable<Task>

Session["Tasts"] = tasksQuery.ToArray(); // this is Task[]
...
var tasks = (Task[]) Session["Tasts"]; // this is Task[]
Marc Gravell
I thought it might be something along the lines of .ToList() then putting that in the session. The note about keeping the data-context alive was interesting. Thanks for that :)
Chalkey
A: 

var is not a kind of "dynamic" type, it simply means that the compiler infers the actual type according to the type of the initialization value. The type is determined statically, it is not possible to "cast to var"

Thomas Levesque