5
respostas

contexto.Database.EnsureCreated();

Quando estou startando o projeto, o mesmo está me apresentando o seguinte erro:

System.NullReferenceException: Object reference not set to an instance of an object. contexto was null

5 respostas

Olá, Ricardo

Pode postar aqui o código completo da sua classe, para darmos uma olhada? Assim podemos ter uma ideia melhor do que está acontecendo. Obrigado!

Código abaixo

using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;

namespace CasaDoCodigo
{
    class DataService : IDataService
    {
        private readonly ApplicationContext contexto;

        // Injeção de dependência
        public DataService(ApplicationContext contexto)
        {
        }

        public object JasonConvert { get; private set; }

        public void InicializaDB()
        {

            contexto.Database.EnsureCreated();

            var json = File.ReadAllText("livros.json");
            var livros = JsonConvert.DeserializeObject<List<Livro>>(json);

        }

        class Livro
        {
            public string Codigo { get; set; }
            public string Nome { get; set; }
            public decimal Preco { get; set; }
        }
    }
}
namespace CasaDoCodigo
{
    interface IDataService
    {
        void InicializaDB();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;

namespace CasaDoCodigo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // Conexão com Banco de Dados - Arquivo Startup.cs
            string connectionString = Configuration.GetConnectionString("Default");

            services.AddDbContext<ApplicationContext>(opitions =>
           opitions.UseSqlServer(connectionString)
           );

            services.AddTransient<IDataService, DataService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
            IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default", // Rota Padrão
                                     //template: "{controller=Home}/{action=Index}/{id?}");
                    template: "{controller=Pedido}/{action=Carrossel}/{id?}");
            });

            serviceProvider.GetService<IDataService>().InicializaDB();

        }
    }
}

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software