简体   繁体   中英

Decimal field required in Entity Framework

I have a simple application with asp.net mvc c# and I use EF code first.

I have a class "Student" that has a property of type decimal and others of type int. I dont undrestand why the decimal property will be not null without any data annotation?

Another problem is that when i run my application, the text box with decimal property retrieves a value of 170,6 but when I submit it, it shows an error which says that 170,6 is not a valid value and I have to change it to 170.6 to be able to submit.

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public byte[] Photo { get; set; }
    public decimal Height { get; set; }
    public int Weight { get; set; }
    public int changement { get; set; }

    public Grade Grade { get; set; }

}
public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }

    public ICollection<Student> Students { get; set; }
}

I dont understand why the decimal property will be not null without any data annotation

decimal in C# is a value type. It simply cannot be null . As would for instance int , double , DateTime .

170,6 is not a valid value and I have to change it to 170.6 to be able to submit.

That's a usual problem of Culture / Locale. I'm looking for a nice duplicate question on this topic, to give a useful link on how to solve this.

It's a bit tricky, because MVC has to generate the validation code that would be on client side to allow submitting, and the client could be configured with another culture.

EDIT : you can have a look at this question and it's accepted answer : MVC/JQuery validation does not accept comma as decimal separator

For the first problem, a decimal is a value type, and can never be null. If you want it to be null, you should define it as decimal? (which is a shortcut for the Nullable<decimal> reference type wrapper). Make sure the corresponding field in the database is also NULL .

For the second problem, you should make sure your request thread runs at the same culture as your client. There are many ways to do it, try looking up on this site or google.

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