简体   繁体   English

参数超出十进制SQL Server EF C#的范围异常

[英]Argument out of range exception for decimal SQL Server EF C#

I am either going crazy or missing something entirely here. 我要么疯了,要么完全错过了这里的东西。 I have a time entry I am trying to submit with a "TimeWorked" attribute whose data type in the SQL server is decimal(4,2). 我有一个时间条目我试图提交一个“TimeWorked”属性,其SQL服务器中的数据类型是十进制(4,2)。

When I try to add a time entry with 10.00 as the value for TimeWorked, I get the following error. 当我尝试添加10.00作为TimeWorked的值的时间条目时,我收到以下错误。

Error 错误

在此输入图像描述

Code To Insert 要插入的代码

using (var context = new ProjectTrackingDb())
{
    TimeEntry entry = new TimeEntry
    {
        ProjectName = SelectedProject.ProjectName,
        Phase = SelectedProject.Phase,
        Code = SelectedClassification.Code,
        TimeWorked = TimeEntry.TimeWorked,
        Description = TimeEntry.Description,
        UserName = CurrentUserName,
        Date = TimeEntry.Date
    };
    context.TimeEntries.Add(entry);
    context.SaveChanges();  
}

Database Model 数据库模型

[Table("TimeEntry")]
public partial class TimeEntry
{
    [Key]
    public int EntryID { get; set; }

    public decimal TimeWorked { get; set; }

    [Column(TypeName = "text")]
    [Required]
    public string Description { get; set; }

    [Column(TypeName = "date")]
    public DateTime Date { get; set; }

    [StringLength(20)]
    public string UserName { get; set; }

    [StringLength(30)]
    public string ProjectName { get; set; }

    [StringLength(30)]
    public string Phase { get; set; }

    [StringLength(2)]
    public string Code { get; set; }
}

Database data types: 数据库数据类型:

在此输入图像描述

What I have tried: 我尝试过的:

I have tried a few things. 我尝试了一些事情。 I tried adding a Range(0,10) data annotation to the model for the database. 我尝试将Range(0,10)数据注释添加到数据库的模型中。 I increased the precision of the decimal to (18,4) just to see if it would accept it. 我将小数的精度提高到(18,4)只是为了看它是否会接受它。

I was able to manually insert a value of 10 into the database directly in SSMS so I am not quite sure how that is working but my code to insert does not? 我能够直接在SSMS中手动将值10插入到数据库中,所以我不太确定它是如何工作的但我的代码插入不是?

Edit 编辑

I also tried adding 10 directly to the timeworked attribute from my code and it still threw the error. 我还尝试将10直接添加到我的代码中的timeworked属性,它仍然抛出错误。 I am inspecting the data before inserting and it shows up as 10 as well. 我在插入之前检查数据,它也显示为10。

As suggested in the comments of the question I set the precision using model builder in entity framework to match the precision of my database. 正如问题的评论中所建议的那样,我在实体框架中使用模型构建器来设置精度,以匹配我的数据库的精度。

Thank you to everyone for helping me arrive at this answer. 感谢大家帮我解决这个问题。

Code

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Entity<TimeEntry>().Property(e => e.TimeWorked).HasPrecision(4, 2);
     base.OnModelCreating(modelBuilder);
 }

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

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