1

A User who logs in to the system using functions in the Users class. now i need to read the User's fields (UserID, FullName, GroupID...) from other classes and this seems to me a bit complicated... i cannot use static variables in the users class because they will stay in the memory till the appdomain is recycled and of course i cannot instantiate a new user object because i need the info that have been already instantiated.

how can i retrieve the Users fields / properties from other class?

adiga
  • 34,372
  • 9
  • 61
  • 83
Jeremy
  • 53
  • 6

1 Answers1

0

You'll want to store something that references the logged-in user, for example their UserID, within the ViewData or TempData. This will allow you to retrieve their info from your database based on their UserID.

Then in the classes that need to read this user's data, you will instantiate a User object (whatever you have named it) and populate the object's properties with data from the database for this user.

Community
  • 1
  • 1
Jerreck
  • 2,930
  • 3
  • 24
  • 42
  • Well yes exactly! but the thing is that i was trying to reduce the amount of database connections and so i thought to save all those info in the classes attributes – Jeremy Jan 15 '16 at 17:45
  • besides everytime that i need to get the user info i have to instantiate a Users class. Static could be a perfect solution if it serves only the unique request – Jeremy Jan 15 '16 at 17:54
  • In that case, if this is just temporary, you could look at storing a Dictionary or as your own generic data structure in ViewData, but it will eat up your server's memory if you have a large number of users being stored here at once. Honestly, unless you just have very poor performance with your network or DB server, you may be straying into micro-optimization here - just a fair warning. – Jerreck Jan 15 '16 at 18:00
  • 1
    yes you're right! i also found other threads recommending almost the same solution http://stackoverflow.com/questions/14723486/static-fields-vs-session-variables – Jeremy Jan 15 '16 at 18:19