Share via


c# MVC how to display and edit User Roles, User Claims, Roles?

Question

Friday, April 12, 2019 1:34 AM

Have a solution in vb.net webforms.  But now in MVC using entity framework? Stuck trying a zillion ways to make this simple task work.  

this code should return a simple list of the users found in the identity table, it crashes at runtime,

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication31.Models;

namespace WebApplication31.Controllers
{
    public class RoleController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Role
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

error at runtime: 

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'WebApplication31.Models.ApplicationUser'.

UPDATE: this was because of of a declaration in the identity model for another table.  Gets past this error now

The database has the pre defined tables:

dbo.AspNetRoles

dbo.AspNetUserClaims

dbo.AspNetUserLogins

dbo.AspNetUserRoles

dbo.AspNetUsers

I have searched dozens of sites over several days trying to find any example in mvc that will just run.  In each case the example has some elaborate design with extra fields, renaming these default tables and making about 8+ controllers with all sorts of methods.  Try using one solution, it will not compile or it cannot find some custom part,

should be able to have an index and say:

public async Task<ActionResult> Index()
{
return View(await UserManager.Users.ToListAsync());
}

but I cannot get past the previous error, multiple sets per type are not supported.  cannot get past this.  Just a simple basic user/role/userrole app.  I couldnt make the VB solution items work in mvc

Have possible solutions, but I put them and  Visual studio crashes at runtime saying cshtml syntax is wrong when its not? 

ine 7: @Html.ActionLink("Create New Role", "Create") | @Html.ActionLink("Manage User Role", "ManageUserRoles")
Line 8: <hr />
Line 9: @ foreach (var role in Model)
Line 10: {
Line 11: @role.Name @role.Name

And then as there are a total of 3 visual studio instances open?  mine just 'goes away' and then 2 instances remain.  This seems to be part of it. Cant make it work because the visual studio doesnt put the right code that its supposed to.

All replies (37)

Friday, April 12, 2019 11:36 AM

Your post is very confusing.

The error message indicates that you've defined two DbSets of the same type in the DbContext.

Additional information: Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'WebApplication31.Models.ApplicationUser'.

UPDATE: this was because of of a declaration in the identity model for another table.  Gets past this error now

Your past this error and have another issue?  Or you have the same error?

Is there any way you can post your entire project so we help you debug?


Friday, April 12, 2019 4:42 PM

Ok Im past the initial problem of the multiple object sets;  here is the code:

@{
    ViewBag.Title = "Create";
}

<h4>Create Role</h4>
<br /><hr />
@ViewBag.ResultMessage
<br />
<hr />
@Html.ActionLink("List Roles", "Index") | @Html.ActionLink("Manage User Role", "ManageUserRoles")
<hr />
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div>
        Role name
    </div>
    <p>
        @Html.TextBox("RoleName")
    </p>
    <input type="submit" value="Save" />

using System;
using System.Linq;
using System.Web.Mvc;
using WebApplication31.Models;

namespace WebApplication31.Controllers

{
    public class RolesController : Controller
    { public ApplicationDbContext context = new ApplicationDbContext();
        // GET: Roles
        public ActionResult Index()
        {
            var roles = context.Roles.ToList();
             return View(roles);
            //return View();
        }


        // GET: /Roles/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Roles/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
                {
                    Name = collection["RoleName"]
                });
                context.SaveChanges();
                ViewBag.ResultMessage = "Role created successfully !";
                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                ViewBag.ResultMessage = "ERROR- Message details: " + ex.Message + " And: " + ex.InnerException; 
                return View();
            }
        }


    }
}

the applicationdbcontext is just pointing to the SQL database that has the EF asp.net Identity tables original aspNet tables?  It never writes. because Discriminator column,  problem: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Discriminator', table 'MAstr1.dbtest.dbo.AspNetRoles'; column does not allow nulls. INSERT fails.


Friday, April 12, 2019 6:07 PM

Currently the problem is there is a mismatch between the type of columns Roles expects, versus the columns there in the EF AspNetRoles table.

Dont know why Discriminator is put there as a non-null.  Cant remove it because of FK constraints.  Dont know how to match the table, and dont know the commands to use to delete the EF tables and let them be re-cast Will have to make a new database and leave these unless commands to  destroy the database can be figured out.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       


Friday, April 12, 2019 6:24 PM

Are you trying to implement a role manager again?

https://forums.asp.net/t/2152387.aspx

Add the Role Manager in the OWIN configuration in your IdentityConfig.cs file

    public class ApplicationRoleManager : RoleManager<IdentityRole>
    {
        public ApplicationRoleManager(IRoleStore<IdentityRole, string> store) : base(store)
        {
        }
        public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
        {
            var roleStore = new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>());
            return new ApplicationRoleManager(roleStore);
        }
    }

Invoke the configuration in the Startup.Auth.cs file.

        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

Implementation.

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using MvcIdentityDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace MvcIdentityDemo.Controllers
{
    public class RolesController : Controller
    {
        private ApplicationRoleManager _roleManager;

        public RolesController()
        {

        }

        public RolesController(ApplicationRoleManager roleManager)
        {
            RoleManager = roleManager;
        }

        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set
            {
                _roleManager = value;
            }
        }

        // GET: Roles
        public ActionResult Index()
        {
            List<IdentityRole> roles = RoleManager.Roles.ToList();
            return View(roles);
        }

        // GET: Roles/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Roles/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Roles/Create
        [HttpPost]
        public async Task<ActionResult> Create(string Name)
        {
            IdentityRole role = new IdentityRole(Name);
            var result = await RoleManager.CreateAsync(role);
            return RedirectToAction("Index");
        }

        // GET: Roles/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Roles/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Roles/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Roles/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

Index View

@model List<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>
@{
    ViewBag.Title = "Index";
}

<h4>Index</h4>

<div>
    @foreach(var item in Model)
    {
        <div>@item.Name</div>
    }
</div>
<div>
    @Html.ActionLink("Create Role", "Create")
</div>

Create View

@model  Microsoft.AspNet.Identity.EntityFramework.IdentityRole
@{
    ViewBag.Title = "Create";
}

<h4>Create</h4>

@using (Html.BeginForm())
{
    <div>
        Enter a role name: @Html.TextBoxFor(m => m.Name)
    </div>
    <div>
        <input type="submit" value="Create Role" />
    </div>
}

Use the UserManager to add users to roles and users to claims.

await UserManager.AddClaimAsync(user.Id, new Claim("ClaimRole", "Admin"));

Friday, April 12, 2019 8:59 PM

Are you trying to implement a role manager again?

Yes.  and couldnt get the VB one to work here, which was the goal.

https://forums.asp.net/t/2152387.aspx

Add the Role Manager in the OWIN configuration in your IdentityConfig.cs file

yes had this in there, had 'manager' instead of roleStore but almost identical

    public class ApplicationRoleManager : RoleManager<IdentityRole>
    {
        public ApplicationRoleManager(IRoleStore<IdentityRole, string> store) : base(store)
        {
        }
        public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
        {
            var roleStore = new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>());
            return new ApplicationRoleManager(roleStore);
        }
    }

Invoke the configuration in the Startup.Auth.cs file.

Yes had this because Microsoft doesnt generate the Roles component right?

        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

Implementation.

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using MvcIdentityDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace MvcIdentityDemo.Controllers
{
    public class RolesController : Controller
    {
        private ApplicationRoleManager _roleManager;

        public RolesController()
        {

        }

        public RolesController(ApplicationRoleManager roleManager)
        {
            RoleManager = roleManager;
        }

        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set
            {
                _roleManager = value;
            }
        }

        // GET: Roles
        public ActionResult Index()
        {
            List<IdentityRole> roles = RoleManager.Roles.ToList();
            return View(roles);
        }

        // GET: Roles/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Roles/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Roles/Create
        [HttpPost]
        public async Task<ActionResult> Create(string Name)
        {
            IdentityRole role = new IdentityRole(Name);
            var result = await RoleManager.CreateAsync(role);
            return RedirectToAction("Index");
        }

        // GET: Roles/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Roles/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Roles/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Roles/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

Index View

@model List<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>
@{
    ViewBag.Title = "Index";
}

<h4>Index</h4>

<div>
    @foreach(var item in Model)
    {
        <div>@item.Name</div>
    }
</div>
<div>
    @Html.ActionLink("Create Role", "Create")
</div>

Create View

@model  Microsoft.AspNet.Identity.EntityFramework.IdentityRole
@{
    ViewBag.Title = "Create";
}

<h4>Create</h4>

@using (Html.BeginForm())
{
    <div>
        Enter a role name: @Html.TextBoxFor(m => m.Name)
    </div>
    <div>
        <input type="submit" value="Create Role" />
    </div>
}

Use the UserManager to add users to roles and users to claims.

await UserManager.AddClaimAsync(user.Id, new Claim("ClaimRole", "Admin"));

Thanks this is great!!  I put these in there literally, but it fails to update the database, gets the error: 

Cannot insert the value NULL into column 'Discriminator', table  ......dbo.AspNetRoles'; column does not allow nulls. INSERT fails.
The statement has been terminated.

Entity Framework generated an extra column called Descriminator no nulls allowed.  So I have to just add a value in there, since the table cannot be altered in any way.  2nd time I made a mistake on a column, and there is no way to change it, cant even delete the database, the FK  constraint has it locked out, no command known will allow it to be modified or deleted. the database has to remain as "scrap" and a new one generated with a different name, hopefully without the un-needed columns

If there was a SQL command that could force the table(s) to be modified? i could fix this


Friday, April 12, 2019 9:06 PM

dbo.AspNetRoles   show columns:  

Id    Name   Description   Descriminator

How can something be added in to the Descriminator column? how can it be removed?  deleting does not work.  script as:  Drop and insert to-> doesnt work,  SQL admin could not remove it.

Will create a new database and try again


Friday, April 12, 2019 9:39 PM

Yes.  and couldnt get the VB one to work here, which was the goal.

I provided working VB examples if I recall correctly,

yes had this in there, had 'manager' instead of roleStore but almost identical

roleStore is just a variable.

Yes had this because Microsoft doesnt generate the Roles component right?

No, not exactly.  The role manager exists.  It is up to you to turn it on if you wish to use the role manager.

Thanks this is great!!  I put these in there literally, but it fails to update the database, gets the error: 

Cannot insert the value NULL into column 'Discriminator', table  ......dbo.AspNetRoles'; column does not allow nulls. INSERT fails.
The statement has been terminated.

Entity Framework generated an extra column called Descriminator no nulls allowed.  So I have to just add a value in there, since the table cannot be altered in any way.  2nd time I made a mistake on a column, and there is no way to change it, cant even delete the database, the FK  constraint has it locked out, no command known will allow it to be modified or deleted. the database has to remain as "scrap" and a new one generated with a different name, hopefully without the un-needed columns

A discriminator column is generated when there is inheritance.  The column is used to discriminate the stored types.  A discriminator column does not happen out of the clear blue sky.  It happens in response to code that you wrote.

https://www.learnentityframeworkcore.com/inheritance/table-per-hierarchy

If there was a SQL command that could force the table(s) to be modified? i could fix this

I'm not sure how you got to this point or if you are still implementing inheritance but you might be able to fix the project.  One approach is change the database name in the web.config and delete the migration files.  Then do an Add-Migration followed by Update-Database.  This will populate a new database.  Your old DB still exists where you can move the records over using standard DML scripts.

Blowing away the migrations and DB is not an ideal solution when using Code First.  You should move forward or back up then move forward.  I have no idea what steps you took so it's hard to provide an accurate solution.  Sometimes when I'm at the start of a project I'll blow everything away and start over.  But there comes a point where cannot do that anymore and you have to learn how to undo mistakes or fix mistakes.


Saturday, April 13, 2019 4:00 AM

rogersbr

Yes.  and couldnt get the VB one to work here, which was the goal.

I provided working VB examples if I recall correctly,

Yes they worked. point was thats what i wanted to migrate here with css and all but methods didnt work here but did there

rogersbr

yes had this in there, had 'manager' instead of roleStore but almost identical

roleStore is just a variable.

rogersbr

Yes had this because Microsoft doesnt generate the Roles component right?

No, not exactly.  The role manager exists.  It is up to you to turn it on if you wish to use the role manager.

well yes, you have to generate the Roles component, its not instantiated by default in VS2015

rogersbr

A discriminator column is generated when there is inheritance.  The column is used to discriminate the stored types.  A discriminator column does not happen out of the clear blue sky.  It happens in response to code that you wrote.

https://www.learnentityframeworkcore.com/inheritance/table-per-hierarchy

EF generated the tables, but have been having problems with Visual Studio where it crashes, where it produces wrong output, I added nothing, there were extra columns at one time but they were removed, it was default, yet EF generated that.  and EF would not change it, will deal with it some other time.  Great article/info on entity framework

rogersbr

If there was a SQL command that could force the table(s) to be modified? i could fix this

I'm not sure how you got to this point or if you are still implementing inheritance but you might be able to fix the project.  One approach is change the database name in the web.config and delete the migration files.  Then do an Add-Migration followed by Update-Database.  This will populate a new database.  Your old DB still exists where you can move the records over using standard DML scripts.

Blowing away the migrations and DB is not an ideal solution when using Code First.  You should move forward or back up then move forward.  I have no idea what steps you took so it's hard to provide an accurate solution.  Sometimes when I'm at the start of a project I'll blow everything away and start over.  But there comes a point where cannot do that anymore and you have to learn how to undo mistakes or fix mistakes.

in this case the database can be deleted, a new one was made and EF didnt generate that column this time so it sort of works, the Create method does not update the table, but seems like it should. 

        // POST: Roles/Create
        //[HttpPost]
        //public async Task<ActionResult> Create(string Name)
        //{
        //    IdentityRole role = new IdentityRole(Name);

        //    try
        //    {
        //        var result = await RoleManager.CreateAsync(role);
        //        return RedirectToAction("ViewRoles");
        //    }
        //    catch (System.Exception ex)
        //    {

        //        ViewBag.ErrorMessage = "Error trying to save record, " + ex.Message + " and " + ex.InnerException;
        //    }
        //    return RedirectToAction("ViewRoles");
        //}    var result = await RoleManager.CreateAsync(role);

and only the code below writes to the table,

        public ApplicationDbContext context = new ApplicationDbContext();    
        // POST: /Roles/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
                {
                    Name = collection["RoleName"]
                });
                context.SaveChanges();
                ViewBag.ResultMessage = "Role created successfully !";
                return RedirectToAction("ViewRoles");
            }
            catch
            {
                return View();
            }
        }

thought it worked but tracked the table in SSMS, only the bottom of the 2 changed the table, used matching view without any change.  but now it works this way, would like to understand why it wouldnt write the other way


Saturday, April 13, 2019 12:09 PM

And the simple code to see users does not work.  Throws null reference when trying to get users

  public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); <--NULL REFERENCE EXCEPTION
            }
            private set
            {
                _userManager = value;
            }
        }

the offending code:

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult GetRoles(string UserName)
        {
            if (!string.IsNullOrWhiteSpace(UserName))
            {
                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                var account = new AccountController();

                ViewBag.RolesForThisUser = account.UserManager.GetRoles(user.Id); <THIS REFERENCES ACCT CONTROLLER AND CRASHES

                // prepopulat roles for the view dropdown
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                ViewBag.Roles = list;
            }

            return View("ManageUserRoles");
        }

Saturday, April 13, 2019 12:15 PM

Yes they worked. point was thats what i wanted to migrate here with css and all but methods didnt work here but did there

You lost me... this is C#.  The other was VB.NET.

well yes, you have to generate the Roles component, its not instantiated by default in VS2015

Make a request to the ASP team to add the Role Manager to the Identity template.  

thought it worked but tracked the table in SSMS, only the bottom of the 2 changed the table, used matching view without any change.  but now it works this way, would like to understand why it wouldnt write the other way

I guess you missed a step.  I retested the code I posted above and it still works as expected. 

I tested your code and it also works but if you missed a step and your code is throwing an exception, you'll never see the error. 

        [HttpPost]
        public async Task<ActionResult> Create(string Name)
        {
            IdentityRole role = new IdentityRole(Name);

            try
            {
                var result = await RoleManager.CreateAsync(role);
                return RedirectToAction("ViewRoles");
            }
            catch (System.Exception ex)
            {

                ViewBag.ErrorMessage = "Error trying to save record, " + ex.Message + " and " + ex.InnerException;
            }
            return RedirectToAction("ViewRoles");
        }

The ViewBag is used to pass data from the controller to a View in the current request.  You are doing a redirect which is a second request.


Saturday, April 13, 2019 1:16 PM

http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

Here is the reference Im using for c#.  I tried converting the vb.net to no avail from the other project.  i just need one lousy user with one lousy role assigned to test it, and of course

it doesnt work.

the reference code for identity is different, I didnt add line by line, just pasted it.  The part:

get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}

is where the null reference is thrown, may need to reference the right one, I have one user listed, it passes in the user and user.id is correct with the hashed user name.

It really shouldnt be this difficult.  will probably just start windowsapp32 in a while, whats a few more days...


Saturday, April 13, 2019 2:35 PM

rogersbr

http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

Here is the reference Im using for c#.  I tried converting the vb.net to no avail from the other project.  i just need one lousy user with one lousy role assigned to test it, and of course

it doesnt work.

You need the VB.NET syntax?

rogersbr

the reference code for identity is different, I didnt add line by line, just pasted it.  The part:

get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}

is where the null reference is thrown, may need to reference the right one, I have one user listed, it passes in the user and user.id is correct with the hashed user name.

Unclear.  You pasted what?  My code?  The linked tutorial?  My best guess is you introduced bugs by making changes to the known working code base.  

If you are using the tutorial then be very careful.  This code is is a bit different than the default template.

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }

The Visual Studio template looks like this at least it does not VS 2017 templates.

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

The OWIN configuration uses the Create Method.

        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

I checked the 2015 Identity Templates and it has similar code.  Since the UserManager property is throwing an exception, I assume there are issues with the OWIN configuration.

I recommend that you review your code for correctness or publish your code base if you want the community to review your code.  


Saturday, April 13, 2019 7:07 PM

Will re install visual studio.  it doesnt go very long before it crashes, sends the error report and restarts, its every few hours now.  it would create clearly wrong cshtml code recently, it would fail when the code was fine.  come back after restart, the same code would work?  when it would not compile before?  I just wore it out.

when I use the code, I dont add anything.  I put it literally as its shown.  


Saturday, April 13, 2019 7:18 PM

Will re install visual studio.  it doesnt go very long before it crashes, sends the error report and restarts, its every few hours now.  it would create clearly wrong cshtml code recently, it would fail when the code was fine.  come back after restart, the same code would work?  when it would not compile before?  I just wore it out.

when I use the code, I dont add anything.  I put it literally as its shown.  

You have a lot of issues with code generators breaking your code.

You might want to install VS 2019 as it has the latest templates.

https://visualstudio.microsoft.com/downloads/


Saturday, April 13, 2019 9:18 PM

I will try that.  It appears that the template for Entity Framework has been modified.  with a new webapplication33 project and empty database, I run and click register, it generates the 6 tables, but the User table had 7 extra columns that I was going to add to make it compatible with another project.  I made sure these are not present in  this project but it generated them


Saturday, April 13, 2019 9:54 PM

OMG this is how Microsoft has ALWAYS been.  they have to rename and change everything. Instead of MVC being there as an item to choose from? its hidden in a list that you have to try before confirming its MVC

People were too familiar with visual studio so now its totally changed.  Like Windows 8 with no start button.  but as long as it works


Saturday, April 13, 2019 10:55 PM

I will try that.  It appears that the template for Entity Framework has been modified.  with a new webapplication33 project and empty database, I run and click register, it generates the 6 tables, but the User table had 7 extra columns that I was going to add to make it compatible with another project.  I made sure these are not present in  this project but it generated them

Do you have a question or is there a specific problem you are trying to solve?  Did you add properties to the User object and those changes are not reflected in the AspNetUsers table?  Or there are unexpected columns?

OMG this is how Microsoft has ALWAYS been.  they have to rename and change everything.  apparently they no longer support the standard MVC webpage, did away with startup folder, web.config and obscured everything.  Guess VS2017 is the newest version that will handle classical MVC web

People were too familiar with visual studio so now its totally changed

The standard ASP.NET MVC template exists in Visual Studio 2019.  Simply select the "Web' project type. and select the ASP.NET Web Applications.

You must have selected the ASP.NET Core template as ASP.NET Core uses the appsettings.json file and does not have a web.config file.  Select the ASP.NET Web Applications which is what you are familiar with and these projects have the web.config and the template and have a startup folder.

ASP.NET Core is the latest framework and the future of ASP.NET.  


Sunday, April 14, 2019 2:10 PM

rogersbr

I will try that.  It appears that the template for Entity Framework has been modified.  with a new webapplication33 project and empty database, I run and click register, it generates the 6 tables, but the User table had 7 extra columns that I was going to add to make it compatible with another project.  I made sure these are not present in  this project but it generated them

Do you have a question or is there a specific problem you are trying to solve?  Did you add properties to the User object and those changes are not reflected in the AspNetUsers table?  Or there are unexpected columns?

rogersbr

OMG this is how Microsoft has ALWAYS been.  they have to rename and change everything.  apparently they no longer support the standard MVC webpage, did away with startup folder, web.config and obscured everything.  Guess VS2017 is the newest version that will handle classical MVC web

People were too familiar with visual studio so now its totally changed

The standard ASP.NET MVC template exists in Visual Studio 2019.  Simply select the "Web' project type. and select the ASP.NET Web Applications.

You must have selected the ASP.NET Core template as ASP.NET Core uses the appsettings.json file and does not have a web.config file.  Select the ASP.NET Web Applications which is what you are familiar with and these projects have the web.config and the template and have a startup folder.

ASP.NET Core is the latest framework and the future of ASP.NET.  

asp.net Core is the future, but they picked a LOUSY name.  asp.net CORE should be what we've been using the past 10 years.  call it asp.net NEXT GENERATION or something that infers the future, new changes, ability to use linux

we used to have vacuum tube televisions, they worked fine until a tube wore out. you got used to which tube was which symptom, 6GH8A you couldnt have enough of. Take the tubes out and go to Thrifty's and test them and buy whichever.  Then tv's went to transistor modules and those? had to be fixed only in a shop and they added things that werent broke because they didnt know what to fix.  why mention that? I dont know.  

I hope visual studio gets a voice interface, Id say: computer!  (teletype sound) ....working.  Computer, generate a c# web method to manage user roles.  (more teletype sound then it stops) and there is the entire working method on the screen.

Using VS2019 and a new database, now it worked exactly as expected.  no glitches, did not reset, put the correct EF tables and columns in the db, it writes/reads just fine.  In a half hour I did what it took days in vs2015 to do, which didnt work right.   

So far its all working, no strange errors


Monday, April 15, 2019 1:20 AM

Its NOT working, the code writing the user role to a user, the UserManager or the AccountController are not handling the process,

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleAddToUser(string UserName, string RoleName)
        {
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var account = new AccountController();<-- NULL REFERENCE EXCEPTION OBJECT NOT SET TO INSTANCE 
            account.UserManager.AddToRole(user.Id, RoleName);
            
            ViewBag.ResultMessage = "Role created successfully !";
            
            // prepopulat roles for the view dropdown
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            ViewBag.Roles = list;   

            return View("ManageUserRoles");
        }

@{
    ViewBag.Title = "ManageUserRoles";
}

<h4>Manage User Roles</h4>
@Html.ActionLink("Create New Role", "Create") | @Html.ActionLink("Manage User Role", "ManageUserRoles")
<hr/>

<h4>Role Add to User</h4>

@using (Html.BeginForm("RoleAddToUser", "Roles"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <p>
        Username : @Html.TextBox("UserName")
        Role Name: @Html.DropDownList("RoleName", (IEnumerable <SelectListItem>) ViewBag.Roles, "Select ...")

    </p>

    <input type="submit" value="Save" />
}
<hr/>
<h4>Get Roles for a User</h4>
@using (Html.BeginForm("GetRoles", "Roles"))
{
    @Html.AntiForgeryToken()
    <p>
        Username : @Html.TextBox("UserName")
        <input type="submit" value="Get Roles for this User" />
    </p>
}

@if (ViewBag.RolesForThisUser != null)
{
    <div style="background-color:yellow;">
        <h4>Roles for this user </h4>
        <ol>
            @foreach (string s in ViewBag.RolesForThisUser)
            {
                <li>@s</li>
            }
        </ol>
    </div>
}

<hr />
<h4>Delete A User from a Role</h4>

@using (Html.BeginForm("DeleteRoleForUser", "Roles"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <p>
        Username : @Html.TextBox("UserName")
        Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")

    </p>

    <input type="submit" value="Delete this user from Role" />
}

Monday, April 15, 2019 10:31 AM

Its NOT working, the code writing the user role to a user, the UserManager or the AccountController are not handling the process,

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleAddToUser(string UserName, string RoleName)
        {
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var account = new AccountController();<-- NULL REFERENCE EXCEPTION OBJECT NOT SET TO INSTANCE 
            account.UserManager.AddToRole(user.Id, RoleName);
            
            ViewBag.ResultMessage = "Role created successfully !";
            
            // prepopulat roles for the view dropdown
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            ViewBag.Roles = list;   

            return View("ManageUserRoles");
        }

We have been down this path several times in similar threads.  For the third time, Add the following property to make it easy to access the User Manager.  Change YourController  to the name of your controller.

public class YourController : Controller
{
    private ApplicationUserManager _userManager;

    public YourController()
    {
    }
    
    public YourController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ApplicationRoleManager roleManager )
    {
        UserManager = userManager;
    }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

The reason your code is throwing a null is you are using the wrong constructor overload.  However, I recommend adding the property.


Monday, April 15, 2019 11:52 AM

We have been down this path several times in similar threads.  For the third time, Add the following property to make it easy to access the User Manager.  Change YourController  to the name of your controller.

public class YourController : Controller
{
    private ApplicationUserManager _userManager;

    public YourController()
    {
    }
    
    public YourController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ApplicationRoleManager roleManager )
    {
        UserManager = userManager;
    }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

The reason your code is throwing a null is you are using the wrong constructor overload.  However, I recommend adding the property.

I want to understand. I added your code, but it throws a null reference.  it was all working except trying to add a role to a user.  


Monday, April 15, 2019 12:07 PM

I want to understand. I added your code, but it throws a null reference.  it was all working except trying to add a role to a user.  

You did something wrong but I can't see your code.   I built a demo just in case I made a copy mistake.  I simply added the UserManger to the RoleController source code in my post above.  I tested and it returns all the users.  

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using MvcIdentityDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace MvcIdentityDemo.Controllers
{
    public class RolesController : Controller
    {
        private ApplicationRoleManager _roleManager;
        private ApplicationUserManager _userManager;

        public RolesController()
        {

        }

        public RolesController(ApplicationRoleManager roleManager, 
            ApplicationUserManager userManager)
        {
            RoleManager = roleManager;
            UserManager = userManager;
        }

        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set
            {
                _roleManager = value;
            }
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        // GET: Roles
        public ActionResult Index()
        {
            var users = UserManager.Users;
            List<IdentityRole> roles = RoleManager.Roles.ToList();
            return View(roles);
        }

        public ActionResult ViewRoles()
        {
            List<IdentityRole> roles = RoleManager.Roles.ToList();
            return View("Index", roles);
        }

        // GET: Roles/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Roles/Create
        public ActionResult Create()
        {
            return View();
        }

        /* */
        // POST: Roles/Create                   
        [HttpPost]
        public async Task<ActionResult> Create(string Name)
        {
            IdentityRole role = new IdentityRole(Name);
            var result = await RoleManager.CreateAsync(role);
            return RedirectToAction("Index");
        }

        // GET: Roles/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Roles/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Roles/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Roles/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

Monday, April 15, 2019 8:15 PM

I put all the code there literally that you posted, and showed all of the project code thats running so you can see what code is running, but what you didnt seem to post was how to add a role to a user?   Whats amazing is reading the comments, someone found the same exact problem almost 3 years ago, noticed just what I did, and the author said Entity Framework changes, this ran on the old EF but the fix is this:

Posted by: Rogersb on: 6/9/2016 | Points: 25

Hi, the code DOES NOT WORK. Its great and helpful how you explain it, but if you download from github the code will not run, you cannot assign a role to a user. the method is missing to assign a role, and the author makes a mistake in the RolesController around line 101 to 103.

The original code also has a minor glitch in the web.config, pointing to his computer that the user has to point to their own system. 

but if you run the code you can create new roles, but cannot assign to any user. Would you please take a look? 

Posted by: Sheonarayan on: 6/9/2016 | Points: 25

Hi Rogersb,

Thanks!

Entity Framework and the way it works are keep changing, this article code was working at the time of writing this article. Now in order to add roles to the user, you can use below code or as suggested by others (Facebook comment and others)

var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var idResult = um.AddToRole(user.Id, RoleName);

Hope this will help.

Enjoy 

_____________________

just noticed, this and will try


Monday, April 15, 2019 8:53 PM

rogersbr

but what you didnt seem to post was how to add a role to a user? 

As far I understood you were a bit challenged simply firing up the UserManager.  We needed to get that bit fixed first.

Then adding a user to a role is very simple and openly documented.

        public async Task<ActionResult> AddUserToRole(string userId, string theRole)
        {
            var results = await UserManager.AddToRoleAsync(userId, theRole);
            return View();
        }

rogersbr

Now in order to add roles to the user, you can use below code or as suggested by others (Facebook comment and others)

var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var idResult = um.AddToRole(user.Id, RoleName);

You can do that if you want but the UserManager property makes this very simple and declared once.  Your facebook solution runs the risk of multiple DbContexts.  You really should grab the UserManger from the OWIN context.  What's very confusing, is you have used this style of code successfully in other threads.  Not sure why you are struggling to do the same now.


Tuesday, April 16, 2019 2:30 AM

Yes, why I cant make it work now is something to be concerned about.  now with vs2019 the IDE is running fine.  but really the user manager?  is just a black box with unknown parameters. what it does or expects? I dont know, am trying to understand.  Is the code behind set of identity  manager available to see?  

 


Tuesday, April 16, 2019 11:26 AM

Yes, why I cant make it work now is something to be concerned about.  now with vs2019 the IDE is running fine.  but really the user manager?  is just a black box with unknown parameters. what it does or expects? I dont know, am trying to understand.  Is the code behind set of identity  manager available to see?  

 

User manager reference.

/en-us/previous-versions/aspnet/dn613290(v%3Dvs.108)


Tuesday, April 16, 2019 2:11 PM

great reference for Identity Manager there.   I put in the code and it still fails to write, but also throws the null reference exception.  will start another new project and do again


Tuesday, April 16, 2019 2:23 PM

 

User manager reference.

/en-us/previous-versions/aspnet/dn613290(v%3Dvs.108)

In startup we have the following default Identity code, with the rolemanager added

 // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

WHAT DOES this do? its going to instantiate the 4 items so theyre now in physical memory, but to YOU, what does this mean to you as far as identity manager goes?


Wednesday, April 17, 2019 2:58 AM

Finally it works.  So much missing from the example and used the cast UserManager instead of trying to generate another account controller and link it.  so now its able to assign roles and read back.  hoorah.

Next Step now is to put this into a GRIDVIEW


Wednesday, April 17, 2019 11:24 AM

Finally it works.  So much missing from the example and used the cast UserManager instead of trying to generate another account controller and link it.  so now its able to assign roles and read back.  hoorah.

Nothing is missing from the example the example works perfectly fine.

Next Step now is to put this into a GRIDVIEW

There's no GridView in MVC.


Wednesday, April 17, 2019 2:55 PM

rogersbr

Finally it works.  So much missing from the example and used the cast UserManager instead of trying to generate another account controller and link it.  so now its able to assign roles and read back.  hoorah.

Nothing is missing from the example the example works perfectly fine.

rogersbr

Next Step now is to put this into a GRIDVIEW

There's no GridView in MVC.

?? The online example did not work, even its author from years ago says it.  your examples worked perfectly but it was a matter of making the Show Roles and Add user to roles parts, which didnt work because of not using the OWIN context as you had said.

At this point I find a new problem, The project uses 2 different databases.  The new database called DB_User_dat (only for EF login) and the main database ASTR_DB that has many different tables mapped to by several models.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

Now before?  DefaultConnection was set in web.config pointing to the MAIN database.  Now it points to the new Database that has only the 7 Entity Framework Identity tables plus migrations.  

When parts of the project declare the db instance, ApplicationDbContext db as New ApplicationDbContext(); what is needed to point these to the main database?  Or that could be left as-is and just use the new database for Identity and assign that to the Identity logic so that it utilizes that database?


Wednesday, April 17, 2019 3:11 PM

?? The online example did not work, even its author from years ago says it.  your examples worked perfectly but it was a matter of making the Show Roles and Add user to roles parts, which didnt work because of not using the OWIN context as you had said.

Confused my example works but you continue to use an example that did not work?

At this point I find a new problem, The project uses 2 different databases.  The new database called DB_User_dat (only for EF login) and the main database ASTR_DB that has many different tables mapped to by several models.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

Now before?  DefaultConnection was set in web.config pointing to the MAIN database.  Now it points to the new Database that has only the 7 Entity Framework Identity tables plus migrations.  

When parts of the project declare the db instance, ApplicationDbContext db as New ApplicationDbContext(); what is needed to point these to the main database?  Or that could be left as-is and just use the new database for Identity and assign that to the Identity logic so that it utilizes that database?

The forum cannot answer this question.  Scaffold the other two DBs if you wish to include them in the project. 

/en-us/ef/ef6/modeling/code-first/workflows/existing-database


Thursday, April 18, 2019 4:53 PM

rogersbr

?? The online example did not work, even its author from years ago says it.  your examples worked perfectly but it was a matter of making the Show Roles and Add user to roles parts, which didnt work because of not using the OWIN context as you had said.

Confused my example works but you continue to use an example that did not work?

You should not assume so much.  as mentioned I used the example you provided to create the OWIN context and used some of the html of the example code and I added the rest and now it works

The forum cannot answer this question.  Scaffold the other two DBs if you wish to include them in the project. 

/en-us/ef/ef6/modeling/code-first/workflows/existing-database

The forum cannot answer?  I stumped the ASP.NET FORUM!  I should get a t-shirt for that.  Size is 3XL +tall

Its okay I figured it out.  It was so simple, just the db context that was created against a connection string from web.config;  the solution that works is to create another db context to be used when insting Identity and db references. Identity sees all the logins and roles now.

SSMS v2017? has a bug, when looking at the EF tables like aspnetRoles, aspnetUsers, if you select Edit top 100 rows then it shows some old version of whats in the table. If you say Select top 1000 rows? then it shows the actual contents.  They need to be identical but they are not.  This is possibly why the discriminator column error was happening, a bug in SSMS.  Its a side note now, but 2 projects, did the first one and it ran, 2nd project errored out, 2 invalid columns "Discriminator".  No reason, just an SSMS bug.

VS2015 was showing the FULL TOOLBOX contents while showing a controller file.  Tried dragging items onto the controller just to see what would happen but they were getting the X instead of the +.  Currently in this project the toolbox is selected but its empty "there are no usable controls in this group..."   Should toolbox show all the items that are selectable when focus is on a controller full page?  Click on a .cshtml file and the toolbox fills as one would expect.  But to show it on a controller?  seems odd.


Thursday, April 18, 2019 6:16 PM

SSMS v2017? has a bug, when looking at the EF tables like aspnetRoles, aspnetUsers, if you select Edit top 100 rows then it shows some old version of whats in the table. If you say Select top 1000 rows? then it shows the actual contents. 

Nonsense.  The Identity tables are empty by default.  You have to write code or interact with the site to create accounts.

They need to be identical but they are not.  This is possibly why the discriminator column error was happening, a bug in SSMS.  Its a side note now, but 2 projects, did the first one and it ran, 2nd project errored out, 2 invalid columns "Discriminator".  No reason, just an SSMS bug.

As explained above, the Discriminator column is generated through Entity inheritance.  The code you wrote caused the Discriminator column to get generated.

VS2015 was showing the FULL TOOLBOX contents while showing a controller file.  Tried dragging items onto the controller just to see what would happen but they were getting the X instead of the +.  Currently in this project the toolbox is selected but its empty "there are no usable controls in this group..."   Should toolbox show all the items that are selectable when focus is on a controller full page?  Click on a .cshtml file and the toolbox fills as one would expect.  But to show it on a controller?  seems odd.

What do you expect to show in the toolbox when the controller has the focus?  A foreach loop?  Certainly not a text input.


Thursday, April 18, 2019 6:50 PM

rogersbr

SSMS v2017? has a bug, when looking at the EF tables like aspnetRoles, aspnetUsers, if you select Edit top 100 rows then it shows some old version of whats in the table. If you say Select top 1000 rows? then it shows the actual contents. 

Nonsense.  The Identity tables are empty by default.  You have to write code or interact with the site to create accounts.

This is the identity tables that were populated by the working code?  So there are 8 roles and 2 users and 1 user has been assigned 2 roles.  So theyre populated.  as I said, in SSMS if you right click the table and say Edit 200 rows it shows the wrong contents because of a SSMS bug, it shows some previous contents in this case only 5 roles.  The code in the browser shows all 8 roles.  right click and Select top 1000 roles shows all the roles. Same for the other NON EMPTY tables.

rogersbr

They need to be identical but they are not.  This is possibly why the discriminator column error was happening, a bug in SSMS.  Its a side note now, but 2 projects, did the first one and it ran, 2nd project errored out, 2 invalid columns "Discriminator".  No reason, just an SSMS bug.

As explained above, the Discriminator column is generated through Entity inheritance.  The code you wrote caused the Discriminator column to get generated. 

 Same identical code in 2 projects, one fails at runtime with the 2 discriminator column error, the other runs

rogersbr

VS2015 was showing the FULL TOOLBOX contents while showing a controller file.  Tried dragging items onto the controller just to see what would happen but they were getting the X instead of the +.  Currently in this project the toolbox is selected but its empty "there are no usable controls in this group..."   Should toolbox show all the items that are selectable when focus is on a controller full page?  Click on a .cshtml file and the toolbox fills as one would expect.  But to show it on a controller?  seems odd.

What do you expect to show in the toolbox when the controller has the focus?  A foreach loop?  Certainly not a text input.

In Visual Studio the toolbox should not show checkboxes and buttons and labels and 100's of visual items to drag/drop to be used on a CONTROLLER or MODEL.  if these are shown then the Toolbox is empty saying no usable controls in this group.  Only when its in the .cshtml or the HTML type files should all of the toolbox items be displayed.

It shows the VS2015 installation had become corrupt, or its a bug.

If you can show a controller or model.cs file and show the toolbox items displayed? buttons, labels, and the 100s of widgets?  Id like to see it.  I tried to drag something like a button onto the controller to see what it would do, because it was a fluke


Thursday, April 18, 2019 7:15 PM

This is the identity tables that were populated by the working code?  So there are 8 roles and 2 users and 1 user has been assigned 2 roles.  So theyre populated.  as I said, in SSMS if you right click the table and say Edit 200 rows it shows the wrong contents because of a SSMS bug, it shows some previous contents in this case only 5 roles.  The code in the browser shows all 8 roles.  right click and Select top 1000 roles shows all the roles. Same for the other NON EMPTY tables.

As I said, the Identity tables are empty by default otherwise there would be a lot of chatter in the forums.  Either you opened the wrong DB in SSMS or forgot that you populated the tables.

Same identical code in 2 projects, one fails at runtime with the 2 discriminator column error, the other runs

Ok...

At least you are up and running with Visual Studio 2019.


Saturday, April 20, 2019 7:09 PM

rogersbr

This is the identity tables that were populated by the working code?  So there are 8 roles and 2 users and 1 user has been assigned 2 roles.  So theyre populated.  as I said, in SSMS if you right click the table and say Edit 200 rows it shows the wrong contents because of a SSMS bug, it shows some previous contents in this case only 5 roles.  The code in the browser shows all 8 roles.  right click and Select top 1000 roles shows all the roles. Same for the other NON EMPTY tables.

As I said, the Identity tables are empty by default otherwise there would be a lot of chatter in the forums.  Either you opened the wrong DB in SSMS or forgot that you populated the tables.

No.  Actually its just as I described. using SSMS v17.9  havent seen this happen unless tables weren't updated.  Thats not the case. The application sees and changes the data. the Edit feature fetches the wrong data.  simple as that.