Reputation: 2028
I extended the IdentityDBContext to rename the table names, but it looks like i lost the many to many relationship between the users and roles. The LINQ is not picking up the right relationship anymore (p.s. see the intellisence screenshot):
namespace Carbon.Models {
public partial class CarbonEDM : IdentityDbContext<User, Role, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>{
public CarbonEDM()
: base("name=CarbonDB") {
}
public DbSet<Message> Messages { get; set; }
public static CarbonEDM Create() {
return new CarbonEDM();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().ToTable("Users", "dbo");
modelBuilder.Entity<Role>().ToTable("Roles", "dbo");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles", "dbo") ;
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims", "dbo");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins", "dbo");
}
}
}
Update 1
As the answers suggested, there is no navigational properties on Identity roles model, so i tried the following:
var users = from usr in db.Users
select new UserInfoViewModel{
email = usr.Email,
name = usr.Name,
role_name = db.Roles.Find(usr.Roles.FirstOrDefault().RoleId).Name
};
But still im gettin another error: Method 'Carbon.Models.Role Find(System.Object[])' declared on type 'System.Data.Entity.IDbSet
1[Carbon.Models.Role]' cannot be called with instance of type 'System.Data.Entity.Core.Objects.ObjectQuery1[Carbon.Models.Role]
I just want to get a list of all the users and their role.
Upvotes: 0
Views: 118
Reputation: 713
In your user model you can specify a collection of roles and in your role model you can specify a collection of users. This should create navigation properties.
for example:
public class User{
ICollection<Role> Roles {get; set;}
}
And
public class Role{
ICollection<User> Users {get; set;}
}
Then you can use explicit or eager loading to load the roles as needed.
Upvotes: 0
Reputation: 35126
User.Roles
is not a collection of Role objects. Users to Roles is a many-to-many relationship, so between Users and Roles there is IdentityUserRoles
table that has only 2 columns: UserId
and RoleId
- and this is exactly what you are picking up. This is not because you have renamed the tables - this is by default.
To get role objects for user - get all RoleId for this user, then get all roles with provided IDs.
Upvotes: 1