Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 365
magnattic Avatar asked Aug 28 '11 10:08

magnattic


1 Answers

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.

like image 55
Eranga Avatar answered Sep 28 '22 16:09

Eranga