简体   繁体   中英

Any better way of accessing values from database-LinqToSql

Is this a Correct way of accessing values when using Ling to SQL.I tried returning an IQueryable but got an error stating 'DataContext accessed after Dispose.' and hence converted it to a list.Can some one tell if this is ok or suggest me some other answer that you feel will be more efficient. Can i use the same implementation in all other functions that will be fetching data? Please help.

public List<SS_User> Login(string UserName,String Password)
        {


            using (DbContext = new DALDataContext())
            {
                IQueryable<SS_User> User = (from Users in DbContext.SS_Users
                                            where (Users.UserName == UserName && Users.Password == Password)
                                            select Users);

                return User.ToList<SS_User>();
            }
        }

It will do the job. Note that you're making life hard for yourself by being overly specific - you could just do:

return (from user in dB.Users
             where {your test}
             select user).ToList();

But this is not operationally any different.

Thoughts:

  • shouldn't you expect zero or one matches here? Not multiple? (FirstOrDefault / SingleOrDefault)
  • how do I say this.. stop storing passwords . No really; stop it. Salted hashes only.

For info the reason it didn't work when returning IQueryable is that a query is "deferred" - it hasn't been executed yet. If you dispose the data-context ("using") before the query is iterated (foreach, ToList etc) then the query cannot work. It would be like taking a hosepipe off the tap, then walking to the "business end", opening the nozzle, and wondering why no water.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM