问题描述
我有3个表需要与Entity Framework进行映射,我不确定正确的方法。这是我的3个实体: public class User
{
[Key]
public int user_id {get; set;}
public string user_name {get; set;}
public virtual List< Role>角色{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;}
}
请注意,User_Role实体只是表示一个查找表来链接许多角色给单个用户。
使用SQL我只会执行以下操作:
code> SELECT User.user_name,Role.role_name FROM User INNER JOIN User_Role ON User_Role.user_id = User.user_id INNER JOIN角色ON Role.role_id = User_Role.role_id WHERE User.user_id = 123
我对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));
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.
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"));
这篇关于实体框架映射到查找表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!