Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set database column as "Sparse" when using EF Code First Fluent API?

I am working with a system that is using EF code first and I would like to use a number of SQL Server sparse columns on a table. My current solution is to drop the table created by EF and re-add via a script during the database initialization. Is this something that can be configured with Fluent API in a class inherited from EntityTypeConfiguration or other means?

like image 432
cResults Avatar asked Apr 12 '12 12:04

cResults


People also ask

What is column sparsity?

Sparse columns are ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve non-NULL values.

Which data type can be specified with sparse?

A SPARSE column must be nullable and cannot have the ROWGUIDCOL or IDENTITY properties. A SPARSE column cannot be data types like text, ntext, image, timestamp, user-defined data type, geometry, or geography. It cannot have a default value and bounded-to rule.

How can we specify computed generated column in Entity Framework?

The Entity Framework Core Fluent API HasComputedColumnSql method is used to specify that the property should map to a computed column. The method takes a string indicating the expression used to generate the default value for a database column.


1 Answers

If you use Entity Frameworks migrations, you can issue a SQL statement like this in the Up method for the migration that adds the sparse column:

Sql("alter table TableName alter column ColumnName int sparse");

Even if you don't use migrations, any one-time execution of dbContext.Database.ExecuteSqlCommand with the same SQL will work.

Neither way is as nice as if you could explicitly configure the type through EF, but they're still better than dropping and replacing the entire table.

like image 110
Edward Brey Avatar answered Oct 17 '22 16:10

Edward Brey