How to specify EF byte[] in code first longer than 8000 bytes?

Alexander Christov picture Alexander Christov · Jan 14, 2017 · Viewed 7.2k times · Source

I am using EF 6.1.3. Using code first sets a byte[] property in an entity to max. 8000 bytes. Any attempt to make it greater, that is MAX, fails.

HasMaxLength(null) (yes, the parameter is int?) still sets it to 8000, HasMaxLength(int.MaxValue) or any other value greater than 8000 makes EF throw System.Data.Entity.Core.MetadataException:

Schema specified is not valid. Errors: (0,0) : error 0026: MaxLength '2147483647' is not valid. Length must be between '1' and '8000' for 'varbinary' type.

SQL server 13.0.2151 (mssqllocaldb) allows for varbinary(max):

enter image description here

This limit seems too severe to me. Trying to find a reason why it is imposed does not yield a good reason for this too. So, my question is

How a byte[] can be mapped to varbinary(max) in EF code first?

PS: The property is also 'required', but I am not sure if an optional property may be set to varbinary(MAX) either. Anyway, i have not tested this case since it does not make much sense to me.

Answer

Felice Ferri picture Felice Ferri · Nov 19, 2018

Despite the multiple articles that states the solution is to add the following attribute

[Column(TypeName="image")]
byte[] Photo { get; set; }

I found the correct approach to be, adding instead this attribute

[MaxLength]
public byte[] Photo { get; set; }

With the Column(TypeName) recommendation I'll end up getting the following error with SQLCE:

The field Photo must be a string or array type with a maximum length of '4000'