Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First - SQL Injection prevention

I'm using EF's Code First approach with MySQL.

I'm wondering if EF in that approach has built in protection against the SQL Injection, or do I have to create SQL string query in the MySqlCommand and add some parameters to be safe from that attacks ?

I think I don't have to but I'd like to be sure about that.

Edit (code snippets example):

MyContext cont = new MyContext();
cont.Comment.AddObject(new Comment { Content = "my string" });
cont.SaveChanges();

or

string query = "INSERT INTO Comment(Content)VALUES(@myVal)";

MySqlCommand comm = new MySqlCommand(query);
comm.CommandType = CommandType.Text;

comm.Parameters.AddWithValue("@myVal", "my string");
...and later execute that query

The 1st approach is much faster to code for me

like image 608
Tony Avatar asked Nov 26 '13 10:11

Tony


2 Answers

Your first code is SQL Injection proof.

Anything that you pass to EntityFramework are passed as Command in the inner IDbCommand.

But beware, if you are executing direct query with EntityFramework.

A sentence from MSDN.

Although query composition is possible in LINQ to Entities, it is performed through the object model API. Unlike Entity SQL queries, LINQ to Entities queries are not composed by using string manipulation or concatenation, and they are not susceptible to traditional SQL injection attacks. "

like image 128
Kishore Kumar Avatar answered Sep 28 '22 10:09

Kishore Kumar


EF's LINQ to Entities (as used in your first example) takes care of preventing SQL injection attacks.

like image 37
Moho Avatar answered Sep 28 '22 11:09

Moho