3

I need to populate a byte array from a database field using an IDataRecord and i needed help on how to get this done.

public class MyClass
{
   public string Name {get;set;}
   public byte[] ImageData { get; set;}
}

// Data Layer

public MyClass Populate(IDataRecord dr)
{
   var myClass = new MyClass();
   myClass.Name = myDataRecord.GetString(myDataRecord.GetOrdinal("NAME"));
   myClass.ImageData = // Need info on how to load this

}

Thanks for any help

2 Answers 2

10

You can simply cast by using GetValue() method:

public MyClass Populate(IDataRecord dr)
{
   var myClass = new MyClass();

   int ordinal1 = myDataRecord.GetOrdinal("NAME");
   int ordinal2 = myDataRecord.GetOrdinal("IMAGEDATA");

   myClass.Name = myDataRecord.GetString(ordinal1);
   myClass.ImageData = (byte[])myDataRecord.GetValue(ordinal2);
}

EDIT: The GetOrdinal() is necessary for reading the ordinal of a field by name.

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

Comments

0

Is there some reason that you can't use IDataRecord.GetBytes as in

int imageDataOrdinal = myDataRecord.GetOrdinal("ImageData");
long bytesRead = myDataRecord.GetBytes(
                     imageDataOrdinal,
                     0,
                     myClass.ImageData,
                     0
                     length
                 );

2 Comments

Please explain how to set the value of the length parameter
@ Carl Onager: myDataRecord.GetBytes(imageDataOrdinal, 0, null, 0, 0). This is mentioned in the remarks section of the documentation page ('If you pass a buffer that is null, GetBytes returns the length of the row in bytes.'). The 'row' thing is misleading, of course. It should probably read 'blob' or something like that.

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.