0

With Entity Framework from SQL I am accessing a field that its schema says "bit" Now I want to put it in C# code in an int I wrote something like this: Is this correct? or there are other ways?

int myResult = Convert.ToInt32(ef.thatField);
5
  • 4
    Why do you want it as an int instead of a bool? Commented May 20, 2014 at 13:52
  • Bit maps to boolean, so Convert.ToInt32(someBoolean); should work fine. Commented May 20, 2014 at 13:54
  • 1
    @Bobson because requirements says so! Commented May 20, 2014 at 13:56
  • 1
    @DevWannaBe - Strange, but ok. Can't argue with the reqs. Commented May 20, 2014 at 14:03
  • Sometimes the bit can be mapped to bool? instead of bool. Commented May 20, 2014 at 14:06

1 Answer 1

5

maybe you can try this :

    int myResult = ef.thatField ? 1 : 0;
Sign up to request clarification or add additional context in comments.

8 Comments

The OP's example will work, but this is better because it's more explicit about what's happening.
yeah .. it follows the rule "Always keep it simple" @Bobson
Sometimes the bit can be mapped to bool? instead of bool. In this case you can caught the runtime exception.
He didn't mention that it can't.
@HamletHakobyan - If the column is nullable, then the OP needs to tell us what a NULL maps to. After all, he isn't trying to cast it to int?.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.