Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Simple request from controller to MVC 6 EF7 database for Roles doesn't work

$
0
0

You would think the simplest of simple tests to get your app started would work right out of the box. (well, maybe one step after first since this is Identity issue).

In Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

services.AddMvc();

// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}

In appsettings.json:

{"Data": {"DefaultConnection": {"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-MVC6-45d0e803-343a-4e38-8218-534c3d62860c;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  },

In RolesManagementController.cs

namespace MVC6.Controllers
{
    //[Authorize(Roles = Utilities.Security.AdminRole)]
    public class RolesManagementController : Controller
    {

        ApplicationDbContext context;

        public RolesManagementController()
        {
            context = new ApplicationDbContext();

        }

        public ActionResult Index()
        {
            var Roles = context.Roles.ToList();
            return View(Roles);
        }

The "var Roles = context.Roles.ToList();" triggers this error:
Message=No database providers are configured. Configure a database provider by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.

So in Startup.cs I make a partial class at the top to override ConfigureServices:

namespace MVC6
{

   public partial class MVC6Context: DbContext
    {

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            optionsBuilder.UseSqlServer(@"Server=(localdb)\\mssqllocaldb;Database=aspnet5-MVC6-45d0e803-343a-4e38-8218-534c3d62860c;Trusted_Connection=True;MultipleActiveResultSets=true");
        }


    }

//all other startup stuff
//public Startup
//public void ConfigureServices

And I reference it in RolesManagementController.cs like this:

namespace MVC6.Controllers
{
    public class RolesManagementController : Controller
    {
      MVC6Context context = new MVC6Context();

        public ActionResult Index()
        {
            var Roles = context.Roles.ToList();
            return View(Roles);
        }

And. . . . I get this error with ".Roles." underlined:

ErrorCS1061 'MVC6Context' does not contain a definition for 'Roles' and no extension method 'Roles' accepting a first argument of type 'MVC6Context' could be found (are you missing a using directive or an assembly reference?)

So I am at a total loss just to get a simple Index.chstml view returned with a list of roles in my AspNetRoles table.
I can register, login, change password using what came with the Asp NET 5 MVC template for Single User Authentication.
I can make the roles  and assign a role to the admin user with this code I found in a YouTube video (go figure), but I sure can't return a
simple list of Roles. It would be nice to use the "IServiceProvider serviceProvider" like in CreateRoles but I have no idea where it comes from or how to use it.

      private async Task CreateRoles(ApplicationDbContext context, IServiceProvider serviceProvider)
        {
            var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

          
            List<IdentityRole> roles = new List<IdentityRole>();
            roles.Add(new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" });
            roles.Add(new IdentityRole { Name = "Public", NormalizedName = "PUBLIC" });
            roles.Add(new IdentityRole { Name = "User", NormalizedName = "USER" });
            roles.Add(new IdentityRole { Name = "Dev", NormalizedName = "DEV" });

            foreach (var role in roles)
            {
                var roleExist = await RoleManager.RoleExistsAsync(role.Name);
                if (!roleExist)
                {

                    context.Roles.Add(role);
                    context.SaveChanges();

                }
            } //foreach

            var user = await UserManager.FindByIdAsync("51193a3c-28fd-4f18-95bb-08a53d5d6693");

            await UserManager.AddToRoleAsync(user, "Admin");

        }


I will accept any way possible to return just a list of Roles. . . for now. Once that is working, I will work on Edit, Delete, Add.

Thanks if you can help me.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>