0

I am a bit confused and wanted to know technically what exactly happens when i call each of these command, also which is preferable over another.

My scenario is in desktop application, where there is a LoginForm, in which:

  1. User Logs In by giving username, password.
  2. I changed password directly in the database against current user.
  3. User Logs out.
  4. User Logs in again by giving username and new password but context is still holding old password.

PROBLEM STATEMENT: HOW TO GET REFRESH DATA, BELOW IS MY CODE SNIPPET

public partial class LoginForm : Form
{    
    EntitiesModel _context = null;
    public LoginForm()
    {
        InitializeComponent();
    }
    private void LoginForm_Load(object sender, EventArgs e)
    {
        _context = new EntitiesModel(Global.ConnectionString);
    }
    private void btnLogin_Click(object sender, EventArgs e)
    {
        USER user = _context.USERs.FirstOrDefault(u => u.USERNAME == txtUsername.Text.Trim() && u.PASSWORD == txtPassword.Text.Trim());
        // after authentication show main menu etc
    }
    private void btnLogout_Click(object sender, EventArgs e)
    {
        //option 1: i dispose off current context here and create new context each time login button is clicked, so that context fetches latest password from database
        if (_context != null)
            _context.Dispose();

        //option 2: i only release all entities from current context cache and use the same context each time login button is clicked rather creating new context
        _context.cache.ReleaseAll();
    }
}
tango
  • 80
  • 2
  • 11

1 Answers1

1

don't know about the life cycle of your form but the following should do:

public partial class LoginForm : Form
{    

    public LoginForm()
    {
        InitializeComponent();
    }

    private void LoginForm_Load(object sender, EventArgs e)
    {

    }

    private void btnLogin_Click(object sender, EventArgs e)
    {
        using (EntitiesModel context = new EntitiesModel(Global.ConnectionString))
            USER user = _context.USERs.FirstOrDefault(
                u => u.USERNAME == txtUsername.Text.Trim() && 
                     u.PASSWORD == txtPassword.Text.Trim());
            // after authentication show main menu etc
        }
    }

    private void btnLogout_Click(object sender, EventArgs e)
    {

    }
}

use short scope context <=> create it when needed then release it to avoid:

  • database lock;
  • context growth in memory.

You should store a currentUser in app memory, and set currentUser to null for logout. For this you have to attach the current user to a context when needed.

tschmit007
  • 7,559
  • 2
  • 35
  • 43
  • Hi Sir thanks for your reply, in-fact using statement is a much better approach as advised by you. but suppose if my context life cycle is not ending here so what is suitable to do to get refreshed data, either disposing context or releasing 1st level cache explicitly. – tango Nov 27 '15 at 07:44