I'm trying to store/save an image in an SQL Compact Edition (CE) database.
I declare the field in my Student model as:
[Column(TypeName = "image")]
public byte[] Photo { get; set; }
The database is created with the image data type for the Photo column as can be seen here:
The problem is:
When I run the app and try to save a Student with a Photo of 3 MB (for example), I get an exception:
validationError.ErrorMessage = "The field Photo must be a string or array type
with a maximum length of '4000'."
SQL Server CE supports these Data Types. In this comparison between SQL Express and SQL Compact Edition (CE) we have that SQL CE supports Binary (BLOB) storage through the use of image data type.
Image = Variable-length binary data with a maximum length of 2^30–1 (1,073,741,823) bytes. Storage is the length of the value in bytes.
Image should do the job I think.
What am I doing wrong here? Is this a bug?
Note:
I also tried the MaxLength data annotation:
[Column(TypeName = "image")]
[MaxLength(int.MaxValue)]
public byte[] Photo { get; set; }
but I get this exception:
Binary column with MaxLength greater than 8000 is not supported.
Edit:
I found the post about the release of EF 4.1. It has the following:
Change of default length for non-key string and binary columns from ‘128’ to ‘Max’. SQL Compact does not support ‘Max’ columns, when running against SQL Compact an additional Code First convention will set a default length of 4000. There are more details about the change included in a recent blog post (link below).
Well well well... the only way I could get it working was doing what is described here, that is, setting DbContext.Configuration.ValidateOnSaveEnabled = false
. This is a workaround as the post suggests.