bircastri
bircastri

Reputation: 2167

How can convert byte data to String with EntityFramework

I have a web service in .NET. With this ws, I can receive the image in Base64, I stored it into my database throught Entity Framework. To do this, I convert this String in Byte. With this code:

    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

Now, I must get this data from database and show it from ws. So I have this code to retreive the data and print the response:

private IQueryable<ImmaginiSecSocDTO> getSecSocData(int? id)
{
    if (id != null)
    {
    return from u in db_data.CAMERA_SEC_SOC 
           where u.ID == id
           select new ImmaginiSecSocDTO()
           {
           image = System.Text.Encoding.UTF8.GetString(u.Image),
           image_width = u.image_width,
           image_height= u.image_height,
           type = u.type,
           rectangle = new ImmaginiSecSocDTO.Rectangle()
           {
             rects = from pi in db_data.CAMERA_SEC_SOC_Rectangles 
                where pi.ID_SecSoc  == id
                select new ImmaginiSecSocDTO.Rectangle.Rect()
                {   
                height= pi.height,
                width = pi.width,
                x = pi.x,
                y=pi.y
                }
           } 
           };
    }
    return null;
}

But if I try to run it I receive this error message:

"ExceptionType": "System.NotSupportedException", "StackTrace": " in System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.DefaultTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n in System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n in System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n in System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n

Upvotes: 0

Views: 2697

Answers (1)

Neville
Neville

Reputation: 433

My sympathies go out to anyone working with byte[] data through either SQL Server or Entity Framework.

Luckily for you, this question uses the same GetBytes code as this answer, the reason I recognised it is that I used it myself some years ago, and it worked well.

There is of course some open questions about which machine the code was originally encoded on etc. but by the sounds of things, this shouldn't affect you. If it does, then I recommend you try the MemoryStream class, and read using a StreamReader. This will interpret the null line endings a lot better.

Upvotes: 1

Related Questions