Entity Framework Mapping to Lookup table

ε祈祈猫儿з 提交于 2019-12-01 05:09:21

问题


I have 3 tables that need to be mapped with Entity Framework and I'm not sure the proper way to go about this. Here are my 3 entities:

public class User
{
   [Key] 
   public int user_id {get; set;}
   public string user_name {get; set;}

   public virtual List<Role> roles {get; set;}
}

public class Role
{
   [Key] 
   public int role_id {get; set;}

   public string role_name {get; set;}
}

public class User_Role
{
   [Key] 
   public int user_role_id {get; set;}

   public int user_id {get; set;}
   public int role_id {get; set;}
}

Please note that the User_Role entity just represents a lookup table to link many roles to a single user.

With SQL I would just do something like:

SELECT User.user_name, Role.role_name FROM User INNER JOIN User_Role ON User_Role.user_id = User.user_id INNER JOIN Role ON Role.role_id = User_Role.role_id WHERE User.user_id = 123

I am relatively new to Entity Framework so I'm not sure the best way to tackle this using EF4 DbContext (and possibly Fluent API?) but I'm hoping its pretty straight forward.

Thanks in advance.


回答1:


It turns out I needed to use Fluent API to map a many to many table (User_Role).

     modelBuilder.Entity<Role>()
        .HasMany<User>(u => u.users)
        .WithMany(r => r.roles)
        .Map(m => 
           m.MapLeftKey("role_id")
           m.MapRightKey("user_id")
           m.ToTable("User_Role"));


来源:https://stackoverflow.com/questions/7954738/entity-framework-mapping-to-lookup-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!