Search code examples
entity-frameworkcode-firstdbcontextsparse-matrix

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?


Solution

  • 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.