对于这个模式,我会在sql中编写以下查询,以便以下列方式获取该用户的所有角色,活动和应用程序
select * from users u, roles r, userroles ur, roleappactivities raa, applications ap, activities ac
where u.Id = ur.UserId
and ur.RoleId = r.Id
and r.Id = raa.RoleId
and raa.ApplicationId = ap.Id
and raa.ActivityId = ac.Id
and u.id = 1
为了在我的核心应用程序中实现同样的目的,我已经编写了以下代码,这是失败的。我通过以下代码完成了如何实现上述查询的想法。任何帮助非常感谢。
_context.Users
.Include("Roles")
.Include("RoleAppActivities")
.Include("Applications")
.Include("Activities")
.Where(x => x.Id == id)
.Select(x => new User
{
Id = x.Id,
TId = x.TId,
Roles = x.Roles
})
编辑:
这是我的实体
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<UserRole> Roles { get; set; }
}
公共类UserRole {
public int UserId { get; set; }
public User User{ get; set; }
public int RoleId { get; set; }
public Role Role{get; set;}
}
public class Role
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<UserRole> Users { get; set; }
public ICollection<RoleApplicationActivity> RoleApplicationActivity { get; set; }
}
public class RoleApplicationActivity
{
public int Id { get; set; }
public int RoleId { get; set; }
public int ApplicationId { get; set; }
public int ActivityId { get; set; }
public Activity Activity { get; set; }
public Application Application { get; set; }
public Role Role { get; set; }
}
public class Activity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<RoleApplicationActivity> RoleApplicationActivity { get; set; }
}
public class Application
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<RoleApplicationActivity> RoleApplicationActivity { get; set; }
}
答案 0 :(得分:0)
我认为您的实体用户应该拥有其他收藏品(角色, RoleAppActivities ..)。所以你可以使用.include(user =&gt; user.Collection)直接加载它们,我认为它比使用.include(“string)”更强类型。
答案 1 :(得分:0)
我要修改我的查询以解决问题。
from u in _context.Users
from r in _context.Roles
from app in _context.Applications
from ac in _context.Activities
where u.Id == 1
select u