Is it possible to force Entity Framework Code First to use floats (or doubles) in C# entities, and map them to decimals in SQL Server? There would need to be a conversion, and there could be precision loss going from decimal to float or double, but assuming that is avoidable due to the particular domain, will EF let you do it?
For example, I'd like to have
public class House
{
...
public float Width { get; set; }
}
Map to
CREATE TABLE [dbo].[Houses] (
...
[Width] [decimal](12, 4) NOT NULL
)
Can this be done with EF attributes, the Fluent API, or by some other means?
No, it is not possible to create such a mapping. The decimal
type on SQL Server and float
or double
on .NET are incompatible. That's what the exception says when you try a mapping like
modelBuilder.Entity<House>()
.Property(h => h.Width)
.HasColumnType("decimal"); // Does not work !
Unfortunately, EF does not support any mappings between different primitive types. You are forced to use a type in .NET that is compatible with the column type in SQL Server.
A possible (not very nice) 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; }
}
}
The type casts can throw exceptions if the source numbers do not fit into the target type, so there might be a more sophisticated conversion necessary.
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