[英]How to access many to many mapped table in c# with Entity Framework
I am using EF code-first. 我先使用EF代码。 I have two classes Users
and Roles
which are mapped in a many-to-many relationship as below. 我有两个类“ Users
和“ Roles
,它们以多对多关系映射,如下所示。
public class User
{
public User()
{
this.Roles = new HashSet<Role>();
}
public int UserId { get; set; }
public string UserName { get; set; }
public string PasswordHash { get; set; }
public DateTime? LastLoggedOn { get; set; }
public DateTime? PasswordChangedOn { get; set; }
public int IsActive { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public class Role
{
public Role()
{
this.Users = new HashSet<User>();
}
public int RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
HasMany(r => r.Roles).WithMany(u=>u.Users)
.Map(m =>
{
m.ToTable("UserRoles");
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
});
}
}
Now I want to fetch RoleName
from Roles
with respective to UserId
from Users
现在我想从Roles
RoleName
分别从Users
获取到UserId
I am using this code: 我正在使用此代码:
var roleName = db.Users.Join(db.UserRoles, u => u.UserId, r => r.UserId, (u, r) => new { u, r })
.Join(db.Roles, ur => ur.r.RoleId, q => q.RoleId, (ur, q) => new { ur, q })
.Where(m => m.ur.r.UserId == 1)
.Select(m => new { m.ur.r.UserId, m.q.RoleName });
But it does not allow me to use UserRoles
. 但是它不允许我使用UserRoles
。
Error 错误
'Context' does not contain a definition for 'UserRoles' and no extension method 'UserRoles' accepting a first argument of type 'Context' could be found (are you missing a using directive or an assembly reference?) “上下文”不包含“ UserRoles”的定义,找不到可以接受类型为“ Context”的第一个参数的扩展方法“ UserRoles”(是否缺少using指令或程序集引用?)
Can anyone help me here? 有人能帮我一下吗?
The name of the table you define in the fluent API will only be used (and known) by the database. 您在fluent API中定义的表的名称将仅由数据库使用(并且已知)。 From your application, you should query it by doing : 在您的应用程序中,您应该执行以下操作来查询它:
db.Users.Find(userId).SelectMany(x=>x.Roles).SelectMany(x=>x.RoleName)
Note that this will load all Roles from the user in memory, but this is fine since you will never have 1000 roles for one user I guess. 请注意,这会从用户的内存中加载所有角色,但这很好,因为我猜您永远不会为一个用户拥有1000个角色。
Apart from that, I think that you should only have a 1 to 1 relationship between Roles and Users. 除此之外,我认为角色和用户之间应该只有一对一的关系。 I'd advise to add a UserId column in the role class and to remove the Users collection from this class. 我建议在角色类中添加UserId列,并从此类中删除Users集合。
This way, your query will simply be : 这样,您的查询将简单地是:
db.Roles.Where( x => x.UserId = userId).Select( x => x.RoleName);
And this time, only the Role Names will be pulled into memory. 这次,只有角色名称将被拉入内存。 I think it is also a slightly better design. 我认为这也是一个更好的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.