Entity Framework 6 Code First VarBinary Length in mapping or computed column

code-first ef-fluent-api entity-framework entity-framework-6 sql-server


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:

SQL Computed Length Field

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?

5/23/2017 12:30:54 PM

Accepted Answer

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:

public int? FileSize {get; private set;}
12/15/2015 9:12:00 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow