code first membership provider

你离开我真会死。 提交于 2019-12-03 22:01:39

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!