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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With