I’m using the .NET entity framework and I’ve got one entity containing a varbinary. Is there an easy way to get the size of the varbinary in the codebehind, efter it’s been retrieved from the database?
I’m thinking there might be some way to get the size directly from the entity, something like entity.Context.Size – or do one need to handle it differently?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
A varbinary translates to a byte[] field in Entity Framework, which means you can check the Length property of the array:
int fieldSize = entity.MyVarBinaryField.Length;
As mentioned by tster: In a LINQ to Entities query, you can call the DataLength method of the SqlFunctions class, which will translate into a DATALENGTH function call in the generated SQL statement. This only works with SQL Server and Entity Framework 4 or later:
int? fieldSize = repository.Entity .Select(e => SqlFunctions.DataLength(e.MyVarBinaryField)).Single();
Method 2
I know this question is old, but EF now supports this by using SqlFunctions.DataLength()
Method 3
I solved it by running another query, getting the DATALENGTH() of the cell. Not the smoothest way but it works.
I’m still interested in hearing if anyone can come up with an answer for this though.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0