简体   繁体   中英

ASP.NET MVC 4 - Custom Membership & Role Entities Not Updating

I am developing my first ASP.NET MVC 4 project, using C# and Entity Framework and I wish to implement Custom Membership & Roles, using my own SQL Server database and tables.

I have developed two classes, which are called 'CustomMembershipProvider' (inherits MembershipProvider) and 'CustomRoleProvider' (inherits RoleProvider). Both classes seem to work correctly on their first execution but when I manually update fields within SQL Server (eg change the Right Name or Right Description), the LINQ query I perform on the Entity appears to be out of date.

For clarity, Roles are controlled within my Rights table (tblRights), which contains field names like 'RightName' and 'RightDescription'.

Below is a sample of the code I execute, which returns a string array containing Role/Right values like "Operator" and "Manager":

namespace MyProject.Classes
{
    public class CustomRoleProvider : RoleProvider
    {
        private MyEntities db = new MyEntities();

        public override string[] GetRolesForUser(string username)
        {

            tblOperator _tblOperator = (from prod in db.tblOperators
                                        where prod.Username == username
                                        select prod).FirstOrDefault();

            var roles = _tblOperator.tblOperatorRights.Where(m => m.WorkCentreID == 1).ToArray();

            return roles.Select(m => m.tblRight.RightName).ToArray();
        }
    }
}

Now assuming I manually update SQL Server and change the Role name from "Manager" to "Administrator", the next time this code executes, it will still return "Operator" and "Manager", not "Operator" and "Administrator".

Can anyone see where I am going wrong? You assistance is much appreciated.

Regards, Chris

Thanks to @BenRobinson,

So simple, yet so effective! I am new to C#, so little things like this keep evading me! Thank you! The completed code is below:

namespace MyProject.Classes
{
    public class CustomRoleProvider : RoleProvider
    {
        private MyEntities db;

        public override string[] GetRolesForUser(string username)
        {
            db = new MyEntities();

            tblOperator _tblOperator = (from prod in db.tblOperators
                                        where prod.Username == username
                                        select prod).FirstOrDefault();

            var roles = _tblOperator.tblOperatorRights.Where(m => m.WorkCentreID == 1).ToArray();

            return roles.Select(m => m.tblRight.RightName).ToArray();
        }
    }
}

Regards, Chris

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM