Blankman
Blankman

Reputation: 266950

how to pass a parameter safely into linq to sql

If I want to get a user that has the email address of '[email protected]', how do I pass that as a parameter in linq?

ie.:

var a = from u in Users
        where u.Email = @email
        Select u;

So this would be used in my method:

public static GetuserByEmail(string email)

Do I just pass in the variable or?

Upvotes: 2

Views: 2226

Answers (2)

George Stocker
George Stocker

Reputation: 57872

Linq To SQL automatically handles SQL injection protection for you. It is safe to pass the parameter in as is from the user if you're worried about SQL Injection.

It automatically parametrizes the parameters you pass in and sanitizes them.

If you're worried about XSS, then you can Html.Encode() the output to make sure it is passed back to the UI safely.

public User GetUserByEmail(string email) 
{
    User a = (from u in db.Users
        where u.Email == email
        select u).Single();
    return a;
}

I'm not in front of an IDE at present, so that code may not be syntatically correct all the way through.

Upvotes: 8

Olivier Payen
Olivier Payen

Reputation: 15268

var a = from u in Users
    where u.Email == email
    select u;

Will perfectly work (LINQ to SQL will generate a parametrized SQL query)

PS : you need two '=' for the equals operator

Upvotes: 0

Related Questions