I am relatively new to LINQ queries as I normally just use plain SQL to get my data back but i am changing for the good - Anyway obviously with SQL you pass in parameters so you do not get any SQL injections etc. Now the LINQ query I have written I think is safe but I am thinking it may be able to done a little easier and more efficient.

So I am passing in my data in the query from the model which is being sent from the view and my tables columns are being called from the ProjectLinqDataContext class. Is this safe? is there anything which I am doing which is not best practice.

 var context = new ProjectLinqDataContext();
 var user = from y in context.Customers
               where y.CustomerUsername == model.Email && y.CustomerPassword == model.Password
               select y;

1 Answer 1


Your ProjectLinqDataContext is disposable so make sure to wrap the usage in a using statement. Efficiency will be based on how your database is indexed. The query itself looks fine. You can also use method syntax for a more fluent and object oriented look. This doesn't affect anything, but I think it's much more readable.

using(var context = new ProjectLinqDataContext())
    var user = context.Customers.FirstOrDefault(y => y.CustomerUsername == model.Email && y.CustomerPassword == model.Password);
    //do something with user if it's not null

Make sure your password has been hashed and salted of course.

  • \$\begingroup\$ You should also explain that your code executes the query, while the OP's code doesn't, and why. \$\endgroup\$
    – user92754
    Jun 12, 2016 at 23:24
  • \$\begingroup\$ Thanks for your answer that does look a lot cleaner.. in terms of FirstOrDefault will that return null if no customer is found - this is nice as you don't have to use is .any() all the time? so is kind of like a TOP 1 SQL query? \$\endgroup\$
    – Ted Marley
    Jun 12, 2016 at 23:26
  • \$\begingroup\$ my query does still get the data back @cFrozenDeath.. all held in user object.. so by execute you mean actually performing the query or..? \$\endgroup\$
    – Ted Marley
    Jun 12, 2016 at 23:28
  • \$\begingroup\$ @TedMarley your version represents a delayed executed query, which means you are not asking for it to run immediately. First will throw an Exception if the query returns no elements, FirstOrDefault will return default(T) (null or the Struct default) instead of throwing the exception. FirstOrDefault won't give you an IEnumerable(T) however, just T. \$\endgroup\$
    – user92754
    Jun 12, 2016 at 23:32
  • \$\begingroup\$ ahhhhh @cFrozenDeath thats makes so much sense now!! thanks for explaining that! \$\endgroup\$
    – Ted Marley
    Jun 12, 2016 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.