Entity framework and VARBINARY
Solution 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();
Solution 2
I know this question is old, but EF now supports this by using SqlFunctions.DataLength()
3142 maple
Updated on August 03, 2022Comments
-
3142 maple over 1 year
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?
-
Morten Christiansen about 13 yearsJust a little heads up, this does not work inside a query (as of EF 4.0). It gives the error message: The LINQ expression node type 'ArrayLength' is not supported in LINQ to Entities.
-
bernhof about 13 yearsI'm not sure if it even worked inside a query in EF 1. Marcus L. explicitly asked how to get the size of the varbinary after it's has been retrieved from the database, in which case the above works just fine. If only the size is needed, and not the binary data itself, I would recommend either storing the size in a seperate field, or running a seperate query using the DATALENGTH function, as Marcus ended up doing. In any case, thanks for the heads up :)
-
bernhof over 12 yearsI updated the answer to include an example of retrieving the data length in a LINQ to Entities query (EF 4 only)
-
pseudocoder over 11 yearsI saw that in MSDN but unsure how to implement. Could you give an example?
-
pseudocoder over 11 yearsNevermind, I was just looking in the wrong namespace. Note that the fully qualified name is
System.Data.Objects.SqlClient.SqlFunctions.DataLength()