Tuesday, June 11, 2013

EF 4 and Membership Provider



Asp.Net's MembershipProvider is very useful. It has builtin user role access system , good encryption features and more. To make it work with EF you need to override MembershipProvider. Here is a project that  to make these two work: http://efmembership.codeplex.com/

I chose to use the older version 1.0 which is for EF 4.0  , the latest one works with EF4.2 and it's Code First and I m not very Code First fan , I prefer  to design so I chose Model First . After downloading the project I had to make changes to make it compile. And I also downloaded another tool which helps a lot using EF.

Normally for every single change you make in the  Model , you need to recreate all the tables or get the DDL  Difference and apply the difference script to database , this tools does detect incremental changes and migrare both schema and data so you wont be losing anything:http://visualstudiogallery.msdn.microsoft.com/df3541c3-d833-4b65-b942-989e7ec74c87
It has some bugs though. After making changes in your datamodel in EF you can create the SQL script to apply changes. I use the Table Per Type instead of Table Per Hierarchy.

 Although both EfRoleProvider and EFMembershipProvider classes in the overridden MEmbershipProvider  contain methods commonly needed, I recreated alternative methods as I don't like the signatures of some .
For example instead of passing/retrieving  string array as RoleNames or User names I want to pass/retrieve List<Object> or Collection of objects. This is the overridden GetRolesForUser method which returns a string array, which I think is very impractical:

    public override string[] GetRolesForUser(string username)
And this is my method which returns Role objects as IList: 
  public static List<Role> GetUsersRoles(string userName)
  {
        User user;
        using (Entities entities = new Entities())
        {
            entities.Connection.Open();
user = entities.Users.Include("Roles").FirstOrDefault(p => p.Username == userName);
        }
 
        if (user != null)
        {
            return user.Roles.ToList();
        }
        else
        {
            return null;
        }
    }

No comments:

Post a Comment