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
decimaltype on SQL Server andfloatordoubleon .NET are incompatible. That’s what the exception says when you try a mapping likeUnfortunately, 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:
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.