Can Entity Framework Code First map floats in C # to decimals in SQL Server

Is it possible to force Entity Framework Code to use float (or doubles) in C # objects and map them to decimals in SQL Server? There should be a conversion, and there may be a loss of precision from the decimal point to float or double, but assuming that this can be avoided due to a specific domain, will EF allow you to do this?

For example, I would like to have

public class House { ... public float Width { get; set; } } 

Map for

 CREATE TABLE [dbo].[Houses] ( ... [Width] [decimal](12, 4) NOT NULL ) 

Can this be done using EF attributes, the Fluent API, or in other ways?

+4
source share
1 answer

No, it is not possible to create such a mapping. The decimal type on SQL Server and float or double on .NET are not compatible. This is what the exception says when you try to match, for example

 modelBuilder.Entity<House>() .Property(h => h.Width) .HasColumnType("decimal"); // Does not work ! 

Unfortunately, EF does not support comparisons between various primitive types. You are forced to use a .NET type that is compatible with a column type in SQL Server.

A possible (not very good) workaround is to use two properties in your model class and map only one to the database:

 public class House { // ... private decimal _width; public decimal Width // mapped to database column as decimal { get { return _width; } set { _width = value; } } [NotMapped] // <- not mapped to a database column public float WidthAsFloat { get { return (float)_width; } set { _width = (decimal)value; } } } 

Typecasting can throw exceptions if the source numbers do not match the target type, so a more complex conversion may be required.

+6
source

All Articles