0

I have encountered similar problems with this user: Invalid object name 'dbo.AspNetUsers' in Asp.NET MVC 5 Entity Framework . However, I am not able to find DefaultConnection in server explorer in vs asp.net core 2.2 mvc web app, neither the web config file. What did I do wrong? Did I not connected sql-server properly? Or maybe I did not create the database correctly. I have done a registration page with Identity Core and when I run my app and enter my details to test it I get the same thing: AspNetUsers not found. Thank you kindly, and I really need someone's opinion.

appsettings.json:

  {
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

AccountController for Register and Login views:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using XmlViewer.Models;
using XmlViewer.ViewModels;

namespace XmlViewer.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        [HttpGet]

        [HttpGet]

        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]

        public async Task<IActionResult> Login(LoginViewModel vm)//model binding
        {
            //date din vm sunt bune:
            if(ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(vm.Email, vm.Password, vm.RememberMe, false);//folosit para pt IsPersistent(BOOL)
                if(result.Succeeded)
                {
                    return RedirectToAction("Privacy", "Home");
                }
                ModelState.AddModelError("","Invalid Login. Please Check your username/email or password.");
                return View(vm);
            }
            return View(vm);
        }

        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]

        public async Task<IActionResult> Register(RegisterViewModel vm)//model binding
        {
            if (ModelState.IsValid)
            {

                var user = new ApplicationUser { UserName = vm.Email, Email = vm.Email };
                var result = await _userManager.CreateAsync(user, vm.Password);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, false);
                    return RedirectToAction("Index", "Home");

                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description); //erori de inregistrare in cont
                    }//iterare prin fiecare eroare

                }
            }
            return View(vm);
        }
    }
}

View model for Registration:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using XmlViewer.Models;

namespace XmlViewer.ViewModels
{
    public class RegisterViewModel
    {
        [Required, EmailAddress, MaxLength(256), Display(Name = "Email Address")]//attributes
        public string Email { get; set; }
        [Required, MinLength(6), MaxLength(50), DataType(DataType.Password), Display(Name = "Password")]
        public string Password { get; set; }
        [Required, MinLength(6), MaxLength(50), DataType(DataType.Password), Display(Name = "ConfirmPassword")]
        [Compare("Password", ErrorMessage = "Parolele nu corespund ")]
        public string ConfirmPassword { get; set; }//user input
    }
}

View Model for Login:

using System.ComponentModel.DataAnnotations;

namespace XmlViewer.ViewModels
{
    public class LoginViewModel
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; }
        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
        [Display(Name = "Remember employee account")]
        public bool RememberMe { get; set; }

    }
}

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using XmlViewer.Models;
using Microsoft.AspNetCore.Identity;

namespace XmlViewer
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<XmlViewerContext>()
                .AddDefaultTokenProviders();
            services.AddDbContext<XmlViewerContext>(options => options.UseSqlServer(@"Data Source = (localdb)\ProjectsV13; Initial Catalog = XmlViewer; Integrated Security = True; Connect Timeout = 30;"));
            //Alta baza de date nu master
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Account}/{action=Register}/{id?}");
            });
        }
    }
}
cse
  • 4,066
  • 2
  • 20
  • 37
Alex Godo
  • 79
  • 2
  • 7
  • have you checked for the appsettings.json ? I am not sure if I understand your problem, are you following some tutorial and can share the link so we maybe understand better your problem? – Nicollas Braga Sep 19 '19 at 10:43
  • can you post your appsettings and also the startup.cs and the login code please –  Sep 19 '19 at 10:53
  • I suspect that you do not have generated the database, if this is the case, try running the Entity Framework `add-migration initial` and then `update-database` but this is a shot in the dark, if you update your question with more detailed information, we can help you better – Nicollas Braga Sep 19 '19 at 10:55
  • @NicollasBraga I have indeed followed a tutorial on Identity Core :https://www.youtube.com/watch?v=wBsHaCT18D0&list=PLYMOUCVo86jGwWoSoEkpgnCJ3IPXIQmIC&index=49 – Alex Godo Sep 19 '19 at 12:10
  • @NicollasBraga I have not changed anything in appsettings.json, and the tutorial does not seem to display my problem, but the link in my post is supposed to solve this problems but I can't find DefaultConnection. – Alex Godo Sep 19 '19 at 12:13

1 Answers1

0

You have a hardcode Database connection at startup.cs

services.AddDbContext<XmlViewerContext>(options => options.UseSqlServer(@"Data Source = (localdb)\ProjectsV13; Initial Catalog = XmlViewer; Integrated Security = True; Connect Timeout = 30;"));

your connection string is Data Source = (localdb)\ProjectsV13; Initial Catalog = XmlViewer; Integrated Security = True; Connect Timeout = 30;

try to connect to your database using a sql management tool, you don't need specific the Visual studio server explorer, use the one that you are more familiar, and verify if your model contains/follow the structure you have.

If you are using EF Model First, try to follow this link to understand and create your database model following yours entities.

Nicollas Braga
  • 802
  • 7
  • 27