How to declare an object parameter as null in C#

Asked

Viewed 1,381 times

1

I have the following class in C#

namespace Projeto.Models
{
    public class Biblioteca
    {
        public int Id {get; set;}
        public string Nome {get; set;}
        public Livro Livro {get; set;}
    }

    public class Livro
    {
        public int Id {get; set;}
        public string Titulo {get; set;}
    }
}

Then in the controller I make a query in the database and create an object based on the information that comes from it, and after that I create a JSON with all the generated information

List bibliotecas = new List();

// comandos de SQL e bla bla bla...

while (dados.Read ())
{
    Biblioteca biblioteca = new Biblioteca();

    biblioteca.Id = Convert.ToInt32(dados["IdBiblioteca"]);
    biblioteca.Nome = Convert.ToString(dados["Nome"]);
    biblioteca.Livro = new Livro
    {
        Id = Convert.ToInt32(dados["IdLivro"]),
        Descricao = Convert.ToString(dados["Titulo"])
    };

    bibliotecas.Add (biblioteca);
}

var json = JsonConvert.SerializeObject(bibliotecas);

The big issue is that the book object is not mandatory, IE, can come from the database to its columns null values, only when this happens the system returns me the following error.

Object cannot be cast from Dbnull to other types.

Is there any way to make these two parameters of the book object null when the values do not exist? Why would you need to send the values later indicating that they exist so that javascript is not lost later.

I need JSON to always have the ID and Title keys, even if the values of these two are null. Can I do that? I’ve tried many ways but so far unsuccessful. :(

Thanks for now.

  • If you do this: biblioteca.Livro = dados["IdLivro"] == null ? null : new Livro(){... } doesn’t solve?

  • No, unfortunately it doesn’t solve

  • Matthew... in which line gives the error?

  • Leandro, in this case he does not give me a physical error, but rather logical, I need the JSON to have the two Id and Title keys. So it has to be: { Id: null, Title: null: } or { Id: 123, Title: "Harry Potter" }

3 answers

3

Matthew, in this case it is necessary to treat the value of your Datareader.

Use the command Convert.Isdbnull to verify that the value received is null.

Change the Book Id property to int? to accept null values:

public int? Id { get; set; }

When setting the value of the Book property, validate using the Isdbnull command:

biblioteca.Livro = new Livro 
{ 
    Id = Convert.IsDBNull(dados["IdLivro"]) ? (null as int?) : Convert.ToInt32(dados["IdLivro"]), 
    Descricao = Convert.IsDBNull(dados["Titulo"]) ? null : Convert.ToString(dados["Titulo"]) 
};
  • Would that be something? library.Book = new Book { Id = Convert.Dbnull(data["Idbook"]), Description = Convert.Tostring(data["Title"]) }; it says that I cannot convert from Int to null

  • Note the following: in your Book class, the Id property does not accept null. For Id to accept null you must state it like this: public int? Id { get; set; } Second, to validate with Isdbnull you could do so: library.Book = new Book { Id = Convert.Isdbnull(data["Idbook"]) ? null : Convert.Toint32(data["Idlivro"]), Description = Convert.Isdbnull(data["Title"]) ? null : Convert.Tostring(data["Title"]) }; But this validation only works if your Id field is int?. Otherwise, you will be required to pass some value.

  • I did what you told me, declared in the class the int? and made the ternary operator, but now it returns me this: Error CS0173 Conditional expression type cannot be determined because there is no implicit conversion between "<null>" and "int"

  • Another question, whether in the book class I declare a string? , it returns me the CS8652 error that I have already documented here in the post, follows again: Error CS8652 The 'reference types that allow null value' feature is currently in the Preview Version and without support. To use the Preview features, use the language version of the "Preview version"

  • Try this: library. Book = new Book { id = Convert.Isdbnull(data["Idbook"]) ? (null as int? ) Convert.Toint32(data["Idlivro"]), Descricao = Convert.Isdbnull(data["Title"]) ? (null as int? ) Convert.Tostring(data["Title"]) };

  • Regrettably not Error CS0266 Cannot implicitly convert "int?" to "int". There is an explicit conversion (there is an absent conversion?)

  • Dude, I’ve advised you to put the Id property accepting null values: public int? Id { get; set; }

  • I’m sorry William, I’ve already made so many changes that I didn’t realize that the configuration was missing there. But even so I keep having problems, with the ID that is an int worked 100%, but for the title that is a string? If I do "string?" ,(as previously reported) the system returns me the CS8652 error The 'reference types that allow null value' feature is currently in the Preview Version and unsupported. To use the Preview features, use the language version of the "Preview" ?

  • I sent the example with error. I already edited the post with the correction.

Show 4 more comments

1

If the property that receives the object type Livro which can be null, just indicate this in the declaration of your class.

public class Biblioteca
{
    public int Id {get; set;}
    public string Nome {get; set;}
    public Livro? Livro {get; set;}
}

or

public class Biblioteca
{
    public int Id {get; set;}
    public string Nome {get; set;}
    public Nullable<Livro> Livro { get; set; }
}

And in your case, add verification before trying to add some value to it.

biblioteca.Livro = dados["IdLivro"] != null ? new Livro
{
    Id = Convert.ToInt32(dados["IdLivro"]),
    Descricao = Convert.ToString(dados["Titulo"])
} : null;
  • I tried to do this but Visual Studio returns me this error Error CS8652 The 'reference types that allow null value' feature is currently in the Preview Version and unsupported. To use the Preview features, use the language version of the "Preview version".

  • returns what error?

  • CS8652 Error The 'reference types that allow null value' feature is currently in the Preview Version and unsupported. To use the Preview features, use the language version of the "Preview version".

1

Adjust the Models:

In the model Library, create a constructor that starts Book.

public class Biblioteca
{
    public Biblioteca()
    {
        Livro = new Livro();
    }
    public int Id { get; set; }
    public string Nome { get; set; }
    public Livro Livro { get; set; }
}

In the model Book, allow Null in attribute Id.

public class Livro
{
    public int? Id { get; set; }
    public string Titulo { get; set; }
}

In the controller apply Null check to "Idlivro".

var bibliotecas = new List<Biblioteca>();

// comandos de SQL e bla bla bla...
// Provavelmente dados é um SqlDataReader

while (dados.Read ())
{
    Biblioteca biblioteca = new Biblioteca();

    biblioteca.Id = Convert.ToInt32(dados["IdBiblioteca"]);
    biblioteca.Nome = Convert.ToString(dados["Nome"]);
    if(!dados.IsDBNull(dados.GetOrdinal("IdLivro")))
    {
        biblioteca.Livro.Id = Convert.ToInt32(dados["IdLivro"]);
        biblioteca.Livro.Descricao = dados["Titulo"];
    }

    bibliotecas.Add (biblioteca);
}

var json = JsonConvert.SerializeObject(bibliotecas);

That is, the Library is already born with a Book but with its Null attributes.

Browser other questions tagged

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