Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to execute a SQL command from c#

I have:
SQL
byte[] md5 = ccDc.ExecuteQuery<byte[]>("SELECT HASHBYTES('MD5', ChunkData) FROM  dbo.x where id={0}", myData.Id).FirstOrDefault();

but it gives me the error :

Quote:
The type 'System.Byte[]' must declare a default (parameterless) constructor in order to be constructed during mapping.


when I execute
SELECT HASHBYTES('MD5', ChunkData) FROM dbo.x where Id = '40'

it shows me the md5 I want to read it in my c# code

Can anybody help me?
Thanks
Posted
Comments
Sinisa Hajnal 10-Oct-15 9:47am    
Try to explicitly define array length

1 solution

Have you tried something along these lines?
C#
var select = "SELECT HASHBYTES('MD5', ChunkData) FROM dbo.x where Id = @ID";
var parameter = new SqlParameter("ID", 40);
var query = context.Database.SqlQuery<byte[]>(select, parameter);
var buffer = query.FirstOrDefault();

If you are not required to use Entity Framework then a solution like this might be another option:
Getting binary data using SqlDataReader
 
Share this answer
 
v3
Comments
Richard Deeming 19-Oct-15 11:39am    
Your code is vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
Daniel Miller 19-Oct-15 12:28pm    
Well, yes, obviously you would use a parameterized query in a live system. How to do this was not the question being asked, and my solution was intended to illustrate a specific answer to a specific question as simply as possible. Rather than criticize, perhaps you could have posted a helpful amendment like this:

var select = "SELECT HASHBYTES('MD5', ChunkData) FROM dbo.x where Id = @ID";
var parameter = new SqlParameter("ID", 40);
var query = context.Database.SqlQuery<byte[]>(select, parameter);
var buffer = query.FirstOrDefault();
Richard Deeming 19-Oct-15 12:33pm    
I'm criticizing because your answer introduced a critical security vulnerability into the code, which was not present in the question. My intention was to get you to update your solution with the corrected code, which you have now done.
Daniel Miller 19-Oct-15 12:42pm    
Fair enough - point taken.
Richard Deeming 19-Oct-15 12:43pm    
I've updated my vote, but it might take a while to show up due to caching.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900