I see it is possible to use a query to find a length of a varbinary field in a query.
Entity framework and VARBINARY
But can you map a FileSize property to get the size of a varbinary in the Fluent API without having to write queries?
I want to be able to store some file information in SQL Server. This data is a filename, file contents. This has a definition in the data model as follows:
public class FileData
{
public int Id { get; set; }
public string Filename { get; set; }
public byte[] Contents { get; set; }
}
Typically, I want to know the size of the contents when I retrieve FileData. If I added an int property FileSize to FileData, can you map this property to compute the size?
I can configure this in SQL:
And when I insert into the table it gives me the correct size.
However, if I generate my data model/DbContext using VS2015 -> Add New Item... -> ADO.NET Entity Data Model, my FileData POCO only has an annotation with DatabaseGenerated(DatabaseGeneratedOption.Computed) on the FileSize property. Nothing else reflects the len(Contents) formula I added.
Is it possible to configure this sort of computed column using EF6 Code First?
You can't create computed columns in entity framework code first. The way you're doing it is correct, you just put the DatabaseGenerated(DatabaseGeneratedOption.Computed)
attribute on the property, Entity Framework
won't try to create the column then for you, and you create the column manually. A good idea is to make the property private set, since you won't ever need to manually modify it:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int? FileSize {get; private set;}