Entity Framework C # convert int to bool

I am trying to rewrite a VB.NET WebForms application in C # MVC. I had a problem with one of the properties when using the Entity Framework to instantiate a class.

I have a column in my database "VATInclusive" that is of type "int". The original application implicitly converts the values ​​"1" or "0" to "true" or "false", but when I try to do this, the following error appears in my application:

The "VATInclusive" property in "Shop" cannot be set to "System.Int32". You must set this property to a non-zero value of type "System.Boolean".

I cannot just change the type in the database, as other applications use a table. I tried using the following code to convert the value, but it seems to return only false, regardless of whether the database has “0” or “1” ... Can someone suggest a solution for this?

[Column("VATInclusive")] private int _VATInclusive { get; set; } [NotMapped] public bool VATInclusive { get { if (_VATInclusive == 0) { return false; } else { return true; } } set { if(_VATInclusive == 0) { this.VATInclusive = false; } else { this.VATInclusive = true; } } } 
+5
source share
5 answers

Following the advice of the answers provided, I fixed this question. The problem was the setter accessory, as well as the _VATIncusive property. By changing the code to the following, I managed to get the system to work as I expected.

However, I believe that this is not the best approach, but it works correctly ...

EDIT : EDIT . I reduced access to accessories on the advice of Ryan and hvd ..

EDIT . I am not sure that both properties are set publicly. But I do not think this will be a problem.

  [Column("VATInclusive")] public int _VATInclusive { get; set; } [NotMapped] public bool VATInclusive { get { return _VATInclusive != 0; } set { _VATInclusive = value ? 1 : 0; } } 
+5
source

You have typos on the setter. I think you mean:

 set { if(value == false) { _VATInclusive = 0; } else { _VATInclusive = 1; } } 

Basically, "value" represents the bool value passed to your setter (for conversion to an integer). _VATInclusive is the actual object that you want to change under the hood.

+1
source

You cannot have a setter access assignment to yourself - this will always throw a StackOverflowException. In the code below:

 set { if(_VATInclusive == 0) { this.VATInclusive = false; } else { this.VATInclusive = true; } } 

every time this.VATInclusive is assigned, the control flow returns to the top of the access set. This will obviously never end.

+1
source

In your set you need to compare with value :

 if (value == 0) 
0
source

If you store a column as a bit, the Entity Framework automatically queries it as a boolean for you.

0
source

Source: https://habr.com/ru/post/1205561/


All Articles