chr*_*229 4 mapping lookup entity-framework inner-join entity-framework-4
我有3个表需要与实体框架映射,我不知道正确的方法来解决这个问题.这是我的3个实体:
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;}
}
Run Code Online (Sandbox Code Playgroud)
请注意,User_Role实体只表示一个查找表,用于将多个角色链接到单个用户.
使用SQL我会做类似的事情:
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
Run Code Online (Sandbox Code Playgroud)
我对Entity Framework相对较新,所以我不确定使用EF4 DbContext(以及可能的Fluent API)来解决这个问题的最佳方法,但我希望它非常直接.
提前致谢.
事实证明,我需要使用Fluent API来映射多个到多个表(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"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1688 次 |
| 最近记录: |