Right now I have a static class called universe in my ASP.NET applica开发者_开发百科tion. The universe holds planets and all sorts of other heavenly bodies. When the application starts I want the application to load up most of the database into memory so very few calls will need to be made to the database for the lifespan of the application.
Right now I have several lists inside the static class called universe and I am simply selecting all of the data from each table and throwing them into those Lists of their respective LINQ object. From there I expand upon the LINQ objects using partial classes. However I feel like there should be a better way doing this. Sorry in advance if this is a silly question.
public static List<ss_planets> planets = new List<ss_planets>();
public static List<ss_moons> moons = new List<ss_moons>();
public static void create_the_universe()
{
ssDataContext db = new ssDataContext();
var p = (from s in db.ss_planets select s);
foreach (ss_planets pl in p)
{
planets.Add(pl);
}
var m = (from m in db.ss_moons select m);
foreach (ss_moons mo in p)
{
moons.Add(mo);
}
}
You could use LoadWith to retrieve all the tables you need into memory.
There is nothing wrong with doing it like that in a small application in a read-only situation. If you query these lists heavily and experience performance issues, you should consider creating Dictionaries instead. They allow fast lookup for some key.
You might also consider setting
ssDataContext.ObjectTrackingEnabled = false;
and should wrap the context creation in a using
-statement, which gives you:
using (ssDataContext db = new ssDataContext())
{
ssDataContext.ObjectTrackingEnabled = false;
// do your thing here
}
Disabling object tracking will prevent you from doing things with the entities that you cannot do in this scenario anyway and may decrease initial loading times.
Why not use an in memory database?
static objects on a web site are normally a bad idea as every request could access the static object at the same time
精彩评论