简体   繁体   中英

C# Getting wrong decimal value from EF6 Code-First DB with MySQL

We have a code-first database in our project, with a decimal in one of our models. We set the decimal precision to (6, 2), which we checked in our mysql database's structure. The collation of the db is utf8_unicode_ci .

We saved a value of 4.00 to the database from a view, which was correct. However, now that we try to get the value back from the db, in stead of getting 4.00 or 4.00m , we get 400M . The comma is just gone .

All help appreciated.

(But please, don't suggest dividing by 100. That's ugly fixing and you know it.)

EDIT Model:

public class RSU
{
    public int Id { get; set; }
    public virtual RSUSlot SlotRef { get; set; }
    public decimal? Length { get; set; }
}

INSERT code:

using(dbCOntext db = new dbCOntext())
{
    db.Add(new RSU{ Length = 4.00m });
    db.SaveChanges();
}

GET:

public static CabinetConfig GetCabinet(M4CDbContext db, int id)
{
    return db.CabinetConfig
        .Include(m => m.RSURef)
        .Where(m => m.Id == id)
        .FirstOrDefault();
}

I'm not sure why this isn't working with MySQL but an idea would be:

Use the Fluent API approach and create EntityTypeConfiguration for your class:

public class RSUConfiguration : EntityTypeConfiguration<RSU>
{
    public RSUConfiguration()
    {
        Property(x => x.Length)
            .HasPrecision(6, 2);
    }
}

And add it to your modelBuilder :

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<RSU>().Property(x => x.Length).HasPrecision(6, 2);    
    modelBuilder.Configurations.Add(new RSUConfiguration());

    base.OnModelCreating(modelBuilder);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM