How to use Membership provider with EF Code First? How to use Membership provider with EF Code First? asp.net asp.net

How to use Membership provider with EF Code First?


Have a look at this project

http://codefirstmembership.codeplex.com/

It has entity classes for users and roles, as well as a roleprovider and membershipprovider implementation. If you include the users and roles in your datacontext class the tables will be created in your database.


Your question has two parts.

  1. How to use asp.net membership API with EF code first?
  2. How to preserve existing data when model changes?

as for How to preserve existing data when model changes, as far as with EF 4.0/ asp.net mvc 3, database migrations are not yet supported. You will have to move to asp.net mvc 4.0/ EF 4.3 where database migrations are supported or use similar alternatives , but its still beta release.

asp.net mvc 4.0 database migration in scott gu's blog

Now coming to the point on how to use asp.net membership provider with EF code first. There are couple of challenges :

  1. We cannot/should not do an join with asp.net membership provider tables. Its not recommended, so my suggestion will be to create a "adapter class" for asp.net membership provider classes. For ex :

     public class UserAdapter { // all user related attributes. Not stored in membership schema, but your schema   public string UserProxyName;   // some attributes stored in membership schema   [NotMapped]   public string Email {         get        {              Membership.GetUser(UserProxyName).Email;         }                   }          // some attributes stored in membership schema and not in your schema  [NotMapped]  public string[] UserRoles  {    get    {        return Roles.GetRolesForUser(UserProxyName);    }             }}

    Now for updating information , you may write some functions in Model itself, however i would suggest create a UserRepository with repository design pattern to handle user CRUD operations.

  2. Second challenge is how to create the database on first run. As seeding becomes an issue, if you want to seed user information then seperately running aspnet_regsql is not efficient as membership schema is expected before the seeding happens. I came across this nice article , with some fine tuning it worked for me :

asp.net membership and EF


Currently (EF 4.1 CTP) EF Code First doesn't have that option. It always drops a table if you made changes to model.

Update:

EF 4.1 RTM allows you to create a custom database initializer and specify creation of db objects and data seeding.