odd linq cast exception under a bit load...

auyuksel
auyuksel used Ask the Experts™
on
Hi everyone,
 
I have an asp.net web application has a students table and related entity and I use this GetStudentByLoginID method code block get the student login and
 
have the student object
 
public static Student GetStudentByLoginID(string Email, string password)
 
    {      
 
Student tmp_Student = null;      
 
try
 
        {
 
       
 
var student=(from s in m_DataContext.Students                    
 
where s.Email==Email&&     s.Password==password
 
select s
 
                     );
 
           
 
if(student.ToList().Count>0)
 
                tmp_Student=student.Single();
 
        }
 
       
 
catch ( Exception ex)
 
        {
 
            System.Diagnostics.
 
Debug.WriteLine(ex.Message);
 
           
 
throw ex;
 
        }
 
       
 
return tmp_Student;
 
    }
 
this code works successfully in normal situation, but if 100-150 student want to login the site on same time system have an odd error has call stack:
 
Unable to cast object of type 'System.Int32' to type 'System.String'. System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at DbProcessor.GetStudentByLoginID(String Email, String password) in c:\inetpub\vhosts\xxx\httpdocs\App_Code\App_Code\DbProcessor.cs:line 444 at Login.LoginUser() in c:\inetpub\vhosts\xxx\httpdocs\Login.ascx.cs:line 76 at Login.ibEnter_Click(Object sender, ImageClickEventArgs e) in c:\inetpub\vhosts\xxx\httpdocs
 
and also I had realized that just before this error had occured there was 15-20 of same student object in the cache produced by different student logins,
 
Where I am doing wrong while using this entity, should I use lock statement for the situations like this?
 
Thank you for all your help
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Yes try to use the lock statement

Commented:
Why did you make the function static?
Did you dispose() your datacontext?

Author

Commented:
Because this method is in the DbProcessor class so I can reach all the methods using DbProcessor.Methods(xxx) why is it wrong way to use?
No I did not dispose the data context where and when shoul I dispose it?
Thanks...

Commented:
How did you define m_DataContext?

Author

Commented:
in top of the DbProcessor Class you can see the sample of this class and calling method I have just add the lock statement and also changed  .Single() by .FirstorDefault()
Thanks
Public Class DbProcessor
{
private static DataContext m_DataContext = new DataContext();
private static m_lockobject=new object();
  public DbProcessor()
      {
            //
            // TODO: Add constructor logic here
            //
      }
  public static Student GetStudentByLoginID(string Email, string password)
    {
        //Student tmp_Student = null;
       // System.Diagnostics.Debug.WriteLine(password.GetHashCode().ToString());
        lock (m_lockObject)
        {
            try
            {
                var student = (from s in m_DataContext.Students
                               where s.Email == Email &&
                               s.Password == password
                               select s
                             );

                               return student.FirstOrDefault();
            }
            catch (Exception ex)
            {
                             throw ex;
            }
           
        }
         }

}

Commented:


using(var context = new DataContext)
{
  //Get your data from your context
}

This ensure your datacontext gets disposed. If you put it onside your static funtion every call (and every thread) is using it's own instance of the context.

When you instantiate your context outside the static function (depends on how you did it) every call/thread is using the same context which could result in undiserable results.

I would use static funtions only for helper methods.
Instantiate a datacontext inside a function, I know this will get boring when you have a lot of funtions but it is best practice.

Author

Commented:
Ok , but dbprocessor is a helper class actually and there are many pages on the site using this class
you mean that I should remove this class completely or belove usage of it is ok?
Thanks

Public Class DbProcessor
{
//private static DataContext m_DataContext = new DataContext();
private static m_lockobject=new object();
  public DbProcessor()
      {
            //
            // TODO: Add constructor logic here
            //
      }
  public static Student GetStudentByLoginID(string Email, string password)
    {
        //Student tmp_Student = null;
       // System.Diagnostics.Debug.WriteLine(password.GetHashCode().ToString());
        lock (m_lockObject)
        {
         using(var m_DataContext = new DataContext)
{
 
 try
            {
                var student = (from s in m_DataContext.Students
                               where s.Email == Email &&
                               s.Password == password
                               select s
                             );

                               return student.FirstOrDefault();
            }
            catch (Exception ex)
            {
                             throw ex;
            }
          finally
{
m_DataContext.Dispose();
}
           
        }
   }
         }

}

Commented:
m_DataContext.Dispose(); isn't neccesar, the using statement ensures it gets disposed at the end of the code block.

I think you do not need the lock object anymore. The above code should be ok.

I can't explain why you did have a cast error, maybe this is also solved with the new code.

Author

Commented:
Thank you for your response I am changing the codes but let me clear for one thing please
using (var Context=new DataContext())
{
 ////Some code uses Context
return result;
}

Will this code dispose the context, cause the return statement is inside the using block so using block looks like not ending. Thank you again
Commented:
Yes it will dispose() the context.

Author

Commented:
well , just one more question what about using the context.updatechanges() method? inspite of the fact that disposing context, after geting the entity object how can I update this objects any property?

Author

Commented:
I asked one more question about the issue that I have got no answer.

Commented:
I'm sorry I missed the lasr question, where do you do your updates?

Author

Commented:
I am doing updates locally (not in different helper class) by  using same
using(context   tmp_Context=new context)
{


}
 routine, it works ok.
Thanks

Commented:
That's the right way to do it.

Commented:
I answered your initial question, I answered a second question which would normally be a seperate question.
And you grading me a C for not answering the third one, which you figured out yourself?

Author

Commented:
i didn't think that is important what I grade I just want to attract attention to not being answered.I am new for asking solutions in EE?I will be more carefull about this? it is not personel finally I and I thanked to you many times?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial