1

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

2 Answers 2

1
  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.

Sign up to request clarification or add additional context in comments.

5 Comments

You absolutely correct! Good catch! Thanks for your help!
You are welcome. I am glad that i helped :)
Use parameters, don't concat/interpolate data into a query
@Charlieface That's not concating or interpolating, it's a hard coded value.
@juharr OP is clearly using interpolation in their real code, as indicated by $ and the fact that it doesn't make sense to hard-code a search value like that, even though in the question they have edited the value straight in
0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.