In SQL Server we can write data AS Numeric(15,10)
.. what will the equivalent of this in C#?
I know that Numeric
's equivalent is D开发者_Python百科ecimal
but how to represent Numeric(15,10)
?
There isn't a direct equivalent, in that there are no built-in .NET types which allow you to specify the precision/scale explicitly as far as I'm aware. There's no fixed-point type like NUMERIC.
decimal
and double
are the common floating point types in .NET, with decimal
implementing decimal floating point (like NUMERIC in T-SQL) and double
implementing binary floating point behaviour (like FLOAT and REAL in T-SQL). (There's float
as well, which is a smaller binary floating point type.)
You should choose between decimal
and double
based on what values you're going to represent - I typically think of "man-made", artificial values (particularly money) as being appropriate for decimal
, and continuous, natural values (such as physical dimensions) as being appropriate for double
.
Try looking at this site as a guide to the data type mappings. As far as the precision and length, you control that yourself using format specifiers
There are two answers depending on two questions:
1) What is something that allows you to specify the precision and scale. Nothing. This seems like your question, but just in case:
2) What is something that allows you to specify a decimal floating point number exactly. This is indeed the Decimal type -- but the point is internal and is set to one of 2^32 positions based on the input number. Not sure why, but only 28 values work, or 2^5 - 4..
So even though .Net allows the Decimal to look like a float, it is very different under the covers and does match the Decimal of SQLServer. Anything not a sum of distinct power of 2 values is an estimation using the normal binary floating point. This means even something such as the number 0.1, has already lost precision. But not with the Decimal type.
if you are using EntityFrameWorkCore
there is a solution for this.
after defining DbContext
in your project you can add configuration for the model as below:
public class ChequeEfConfiguration : IEntityTypeConfiguration<Cheque>
{
public void Configure(EntityTypeBuilder<Cheque> builder)
{
builder.Property(a => a.Amount).HasColumnType("decimal(18,2)");
}
}
or you can use OnModelCreating
in your DbContext
like this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Cheque>().Property(x => x.Amount)
.IsRequired().HasColumnType("decimal(18,2)");
}
but I would recommend you to use the first one. for more information visit https://learn.microsoft.com/en-us/ef/core/modeling/
精彩评论