简体   繁体   中英

MembershipUser and Entity Framework Code First

I am playing around with EF Code First and now ran into trouble when implementing a custom MembershipProvider.

For EF Code First I created my own user class like this:

public class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    [Required]
    public string UserName { get; set; }
    [Required]
    public string Password { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public bool IsApproved { get; set; }
    public DateTime? LastLoginDate { get; set; }
    public DateTime? LastActivityDate { get; set; }
    [Required]
    public DateTime CreationDate { get; set; }
    [Required]
    public string ApplicationName { get; set; }
}

I also implemented some functions of my custom MembershipProvider for EF already, but some of them now require MembershipUser as either a parameter or a return value.

    public MembershipUser GetUser(string username, bool userIsOnline)

My first thought was to inherit my User class from MembershipUser , but then I lose the control over the Properties. Would that even work with EF Code First?

An alternate idea is to create a ToMembershipUser() method for my user class. Would that be an option? What would I have to consider?

What's the best way to handle this?

You can use the Adapter Pattern to solve this problem.

public class CustomUser : MembershipUser
{
    public CustomUser(string providername,
                    User userAccount) :
        base(providername,
                        userAccount.UserName,
                        userAccount.Id,
                        userAccount.Email,
                        passwordQuestion,
                        string.Empty,
                        true,
                        false,
                        userAccount.CreationDate,
                        userAccount.LastLoginDate,
                        userAccount.LastActivityDate,
                        new DateTime(),
                        new DateTime())
    {
        UserAccount = userAccount;
    }

    public User UserAccount { get; private set; }
}

Customize the parameters passed to the base constructor depending on what your entity model has.

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