I’m trying to use entity framework together with the default membership “aspnetdb” database.
I’m having trouble with membership and user tables, since I’d like to have a navigational property from membership to user.
I feel like I’ve tried every combination of fluent api mapping, but I must be missing something – or maybe it just can’t be done, when the foreign key is UserId – which is the primary key of both tables as well?
Here’s what I have:
public class Membership {
[Key]
public Guid UserID { get; set; }
public String Password { get; set; }
public virtual User User { get; set; }
}
public class User {
[Key]
public Guid UserId { get; set; }
public String UserName { get; set; }
//public virtual Membership Membership { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<Membership>().ToTable("dbo.aspnet_Membership");
modelBuilder.Entity<Role>().ToTable("dbo.aspnet_Roles");
modelBuilder.Entity<User>().ToTable("dbo.aspnet_Users");
modelBuilder.Entity<User>()
.HasMany(m => m.Roles)
.WithMany(m => m.Users)
.Map(m => {
m.ToTable("aspnet_UsersInRoles");
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
});
//modelBuilder.Entity<Membership>()
// .HasRequired(m => m.User);
//.WithOptionalPrincipal(m => m.Membership).Map(m=>m.MapKey("UserId"));
Database.SetInitializer<EkomiteDBC>(null);
base.OnModelCreating(modelBuilder);
}
The roles are set up fine, and works, but no matter how I try and define the connection between membership and user I keep getting different mapping errors.
I know I’m probably missing something basic, can anyone help?
EDIT: The problem is, it seems, that both “membership” and “users” tables have the primary key “UserID”.
Try this:
Anyway you should not do that at all. Use standard membership API for accessing these tables. These tables are not yours they belong to membership / role API and handling them through EF just removes or breaks functionality the API provides out of the box – in general it will reduce the security because those tables will be available for update in EF and business rules from Membership / Role API will not be enforced.