Search code examples
asp.net-mvc-4code-firstentity-framework-5membership-providersimplemembership

code first membership provider


How can I integrate EF 5.0 with membership provider using code first?

I have my own database schema which I want to use for registration of users etc.


Solution

  • You should take a look at the SimpleMembershipProvider

    It is very easy to use it together with EF.

    Update

    For MVC4 I would start with the blank template.

    you need WebSecurity.InitializeDatabaseConnection to set up the database.

    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "Id", "UserName", true);
    

    It takes as parameters a name of a connectionstring, the table, a unique identifier column and the username-column.

    The model I use for this piece of code above is:

    [Table("Users")]
    public class User
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    
        [Required]
        public string UserName { get; set; }
    
        public string Email { get; set; }
    
        public string FirstName { get; set; }
    
        public string LastName { get; set; }
    }
    

    To log someone in:

     WebSecurity.Login(aUsername, aPassword);
    

    The method above returns a bool, if it is true, login was successfull.

    In the Web.config you do not need to define a membershipProvider as it was with default ASP.NET Membership.

    If you need to gain access to the provider (to delete an account):

    var provider = (SimpleMembershipProvider) Membership.Provider;
    provider.DeleteAccount(aUsername); // Delete the account
    provider.DeleteUser(aUsername, true); // delete the user and its data
    

    For creating a new user (with my given model in this case)

    WebSecurity.CreateUserAndAccount(aUsername, aPassword, new { Email = aEmail, FirstName = aFirstName, LastName = aLastName });
    

    Benefit is, that you can now use your model for other EF classes as a foreign key without having the hassle when you want to do this with the normal asp.net membership. :-)