Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'int?' to 'int'

Tags:

In this query I have 3 records (int-(telefon = d.telefon), decimal-(pesel = d.pesel), decimal-(nip = d.nip)) another records are strings.

public ActionResult detail(int LoginID)
{
    var user = (from d in baza.uzytkowniks
                where LoginID == d.LoginID
                select new uzytkownikModel {
                    imie = d.imie, 
                    nazwisko = d.nazwisko, 
                    telefon = d.telefon, 
                    pesel = d.pesel, 
                    nip = d.nip, 
                    email = d.email, 
                    adres_zamieszkania = d.adres_zamieszkania}).ToList();

    ViewBag.daneuser = user;
    return View();
}

And I have error:

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

and two another errors with 'decimal?' instead 'int?'.

Model:

 public class uzytkownikModel
    {
    [Required]
    public string imie { get; set; }

    [Required]
    public string nazwisko { get; set; }


    public decimal pesel { get; set; }
    public decimal nip { get; set; }

    public string adres_zamieszkania { get; set; }
    public int telefon { get; set; }
    public string email { get; set; }

}

Only imie and nazwisko are nonnullable, rest have allow null

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Now work. I change in model:

   decimal to decimal?

and

int to int?

Thank you everyone for help

like image 940
user1031034 Avatar asked Nov 08 '11 16:11

user1031034


People also ask

What is the use of INT in C#?

int is a keyword that is used to declare a variable which can store an integral type of value (signed integer) the range from -2,147,483,648 to 2,147,483,647. It is an alias of System. Int32.


1 Answers

You'll need to post more code to get a definitive answer, but somewhere one of your variables is nullable, and to assign it to a non-nullable type you need to do .Value.

For example, if your object d's property imie is Nullable<int>, and that is what is causing your problem, you could do this:

imie = d.imie.Value

You will also need to watch for cases where d.imie is null. For example:

imie = d.imie.HasValue ? d.imie.Value : 0

Or, if you like the ?? operator (which evaluates to the first non-null value):

imie = d.imie ?? 0

(I am just using d.imie as an example -- there is not enough code posted to pintpoint the exact problem.)

like image 85
JohnD Avatar answered Sep 17 '22 17:09

JohnD