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?– Thiago Araújo
No, unfortunately it doesn’t solve
– Mateus Mattielo Nickhorn
Matthew... in which line gives the error?
– Leandro Angelo
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" }
– Mateus Mattielo Nickhorn