简体   繁体   English

C#使用MySQL从EF6 Code-First DB获取错误的十进制值

[英]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. 我们将小数精度设置为(6,2),我们在mysql数据库的结构中检查了它。 The collation of the db is utf8_unicode_ci . db的排序规则是utf8_unicode_ci

We saved a value of 4.00 to the database from a view, which was correct. 我们从视图中将值4.00保存到数据库,这是正确的。 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 . 但是,现在我们试图从数据库中获取值,而不是获得4.004.00m ,我们得到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.) (但是,请不要建议除以100.这是丑陋的修复,你知道。)

EDIT Model: 编辑模型:

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

INSERT code: INSERT代码:

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: 我不确定为什么这不适用于MySQL但是一个想法是:

Use the Fluent API approach and create EntityTypeConfiguration for your class: 使用Fluent API方法并为您的类创建EntityTypeConfiguration

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

And add it to your modelBuilder : 并将其添加到您的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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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