开发者

MembershipUser and Entity Framework Code First

开发者 https://www.devze.com 2023-04-01 10:35 出处:网络
I am playing around with EF Code First and now ran into trouble when implementing a custom MembershipProvider.

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 s开发者_如何学运维tring 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号