I'm very new at this, I'd really like some help with this problem:
First I already have a database, say I have 3 tables in this database: User, UserMapping, UserRole. I generated a model with 3 class as follows:
public class user
{
public int UserID { get; set; }
public string UserName { get; set; }
public virtual ICollection<UserMapping> UserMappings { get; set; }
}
public class UserMapping
{
public int UserMappingID { get; set; }
public int UserID { get; set; }
public int UserRoleID { get; set; }
public virtual User User { get; set; }
public virtual UserRole UserRole { get; set; }
}
public class UserRole
{
public int UserRoleID { get; set; }
public string RoleName { get; set; }
public virtual ICollection<UserMapping> UserMappings { get; set; }
}
I want to create a new user, and add a User Role for the new user. User and User Role have no direct relationship. I want to make a view to create a new user, using the User model class with strongly-typed. How can I make a User Role for the user in this view?
Please help...! Thank you very much in advance.
-
Learn the basics first, with pluralsight.gdoron– gdoron2012年04月22日 03:16:08 +00:00Commented Apr 22, 2012 at 3:16
-
1You don't need the UserMapping class it can be inferred from the relationship between User and UserRole. The user has a collection of roles and the roles have a collection of users. Entity Framework will automatically create the supporting table (what you call UserMapping).Craig O– Craig O2012年04月22日 03:25:18 +00:00Commented Apr 22, 2012 at 3:25
1 Answer 1
You don't need to create UserMapping entity by your self . Because when you specify your many to many relationship between User and UserRole EF will automatically create the relationship table UserUserRole
relationship table for you.
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public virtual ICollection<UserRole> UserRoles{ get; set; }
}
public class UserRole
{
public int UserRoleID { get; set; }
public string RoleName { get; set; }
public virtual ICollection<User> Users { get; set; }
}
Then you can map the relationship table to the existing one,
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(u => u.UserRoles)
.WithMany(r => r.Users )
.Map(m =>
{
m.MapLeftKey("UserID");
m.MapRightKey("UserRoleID");
m.ToTable("YourExistinegTableName");
});
}