code first membership provider

2019-04-01 18:39发布

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.

2条回答
淡お忘
2楼-- · 2019-04-01 19:13

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. :-)

查看更多
姐就是有狂的资本
3楼-- · 2019-04-01 19:19

http://msdn.microsoft.com/en-us/library/f1kyba5e

This is actually nothing to do with EF.

EF is just a way to read data.

See also FORMS Authentication http://support.microsoft.com/kb/301240?wa=wsignin1.0

查看更多
登录 后发表回答