我有下面的实体类,我想像sql这样的查询,这与实体框架有什么关系?
select * from SiteUsers su
inner join SiteUserRoles sur on su.Id=sur.SiteUserId
inner join SiteRoleActions sra on sur.SiteRoleId = sra.SiteRoleId
inner join SiteActions sa on sa.Id = sra.SiteActionId
where su.Id=1 and sa.ParentId=189
public class SiteRole
{
public SiteRole()
{
this.SiteActions = new HashSet<SiteAction>();
this.SiteUser = new HashSet<SiteUser>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<SiteAction> SiteActions { get; set; }
public virtual ICollection<SiteUser> SiteUser { get; set; }
}
public partial class SiteUser
{
public SiteUser()
{
this.SiteRoles = new HashSet<SiteRole>();
}
public int Id { get; set; }
public string Email { get; set; }
public string UserPassword { get; set; }
public string UserName { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public Nullable<System.DateTime> DateCreated { get; set; }
public virtual ICollection<SiteRole> SiteRoles { get; set; }
}
public partial class SiteAction
{
public SiteAction()
{
this.Childs = new HashSet<SiteAction>();
this.SiteRoles = new HashSet<SiteRole>();
}
public int Id { get; set; }
public string Name { get; set; }
public string ImagePath { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }
public Nullable<int> ParentId { get; set; }
public Nullable<int> Type { get; set; }
public virtual ICollection<SiteAction> Childs { get; set; }
public virtual SiteAction Parent { get; set; }
public virtual ICollection<SiteRole> SiteRoles { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SiteUser>().HasMany<SiteRole>(r => r.SiteRoles).WithMany(u => u.SiteUser).Map(m =>
{
m.ToTable("SiteUserRoles");
m.MapLeftKey("SiteUserId");
m.MapRightKey("SiteRoleId");
});
modelBuilder.Entity<SiteRole>().HasMany<SiteAction>(r => r.SiteActions).WithMany(u => u.SiteRoles).Map(m =>
{
m.ToTable("SiteRoleActions");
m.MapLeftKey("SiteRoleId");
m.MapRightKey("SiteActionId");
});
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}
答案 0 :(得分:1)
由于您没有SiteUserRoles和SiteRoleActions作为实体,而只是作为连接表(如果我读得很好),您应该使用导航属性而不是加入。类似的东西:
conext.SiteUsers.Where(su => su.id == 1
&& su.SiteRoles.SelectMany(sr => sr.SiteActions)
.Any(sa => sa.ParentId == 189 )
(未进行语法检查)。
答案 1 :(得分:0)
var result= (from su in SiteUsers
join sur in SiteUserRoles
on su.Id=sur.SiteUserId
join sra in SiteRoleActions
on sur.SiteRoleId = sra.SiteRoleId
join sa in SiteActions
on sra.SiteActionId=sa.Id
where su.Id=1 and sa.ParentId=189
select su).ToList();
希望这会有所帮助。结果将是SiteUsers类型的列表。