简体   繁体   中英

Entity Framework Core raw SQL issue

I have a History table with columns C0, C1, C2, C3, TimeStamp .

I want to select a specific column based on input along with corresponding TimeStamp .

Let channelId be 'C2'

var context = new DalModels.DbContext();
string command = "SELECT TimeStamp, @channelId FROM dbo.History";
var user = new SqlParameter("@channelId", channelId);
var result = context.History.FromSql(command, user).ToList();

But instead of a result, I get an exception:

No column name was specified for column 2 of 'h'.

Invalid column name 'C0'.

Invalid column name 'C1'.

Invalid column name 'C2'.

Invalid column name 'C3'.

Invalid column name 'TimeStamp'.

Parameterized query cannot be used for the dynamic column name. Parameters are to be used only on the right-hand-side of expression, eg after an = .

To solve your problem, convert the query to use a variable.

var context = new DalModels.DbContext();
string command = $"SELECT TimeStamp, {channelId} FROM dbo.History";
var result = context.History.FromSql(command, user).ToList();

Note that $ is used for string interpolation

You will then have to whitelist the values that users can pass to the field to prevent SQL injection attacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM