Convert inside a lambda

Asked

Viewed 59 times

-1

I have a nullable int field and that within a lambda I need to popular a nonnullable property. If I do this:

campo1 = Convert.ToInt32(campo2); 

I take this mistake:

Notsupportedexception: LINQ to Entities does not recognize the method 'Int32 Toint32(System.Object)' method, and this method cannot be Translated into a store Expression

How do I load the nullable property from a nullable?

  • What version of EF, young?

3 answers

4


campo1 = campo2 ?? default;

The operator ?? is called null coalescence operator. It will return the left operand if the operand is not null; otherwise it will return the right operand.

  • this default is right, or I should put 0 if it is null?

  • if you want the value 0 when null, default or 0 will be the same thing...

  • Let me get this straight. This already makes a kind of cast for int, right? I don’t need an explicit conversion like I did, right?

  • is not doing a cast.. that code is the equivalent of this: campo1 = campo2.HasValue ? campo2.Value : default;

0

Try using ternary operator in the assignment. Read: campo2 is null ? then 0 else campo2.

int Campo1 = int.Parse(campo2 == null ? "0" : campo2);

Syntax:

condition ? expression1_se_true : expression2_se_false

Take a deeper look here.

0

I resolved it that way:

campo1 = (int)campo2; 
  • 2

    will fail when the field2 is null

  • You should check before if field 2 is null as it is not possible to convert null to int

Browser other questions tagged

You are not signed in. Login or sign up in order to post.