Ben
Ben

Reputation: 383

Linq query FromSql where passing string value

Have a SQL table example column Id-Pk-int, Name-varchar(250), ...

Using EF Core

when I execute

 var data= (from c in _db.Table.FromSql($"select * from Emp where id=1")
                     select c).FirstOrDefault();

returns successfully

but when I execute using where clause name (string)

 var data = (from c in _db.Table.FromSql($"select * from Emp where Name=Mike")
                     select c).FirstOrDefault();

I get an exception, System.Data.SqlClient.SqlException: 'Invalid column name 'Mike'.'

I tested if I changed the data in the database column: Name to 123 (number) it works but fails when value is string

Upvotes: 1

Views: 584

Answers (2)

Charlieface
Charlieface

Reputation: 71309

You should use proper parameterization, do not concatenate or interpolate data into a query, or you will leave yourself open to injection attacks and syntax errors.

var data = (from c in _db.Table.FromSql("select * from Emp where Name = @name",
                   new SqlParameter("@name", SqlDbType.VarChar, 50){Value = "Mike"})
                     select c).FirstOrDefault();


var data = (from c in _db.Table.FromSql("select * from Emp where Id = @id",
                   new SqlParameter("@id", SqlDbType.Int){Value = 1})
                     select c).FirstOrDefault();

In newer versions of EF Core, use FromSqlRaw in the same way.

Upvotes: 0

Batur
Batur

Reputation: 48

  1. I think the problem is occured because of you forgot to use ' symbol. Because exception says there is no column named Mike. And column name should be "Name" as i see from the code.

  2. Check if Name column is VARCHAR. If the column is VARCHAR you need use ' symbols. If not you can use like WHERE ID=1

Use that;

   var data = (from c in _db.Table.FromSql($"select * from Emp where Name='Mike'")
                     select c).FirstOrDefault();

Edit 2: I see that you said Id-int, Name-varchar. Can you use the code i wrote? Thanks.

Upvotes: 1

Related Questions