在 asp.net mvc 中从具有多对多关系的数据库中获取记录

Getting records from the database with many to many relationship in asp.net mvc

This is the structure of the database on which i am working.Click on this text.

我想 select 属于特定类别 ID 的用户的电子邮件 ID 在 MailStatusTable 中提到,其中 MailStatus 列包含 False。

这是我目前得到的查询:

var category = from m in mcontext.MailStatusTable
                             where m.MailStatus == false
                             select new
                             {
                                 CategoryID = m.CategoryID
                             };
            var email_list = from u in mcontext.UserProfiles
                             where u.AnExpert == true
                             where u.AnInstitute == true
                             where category.Contains(u.UserProfileID)

                             select new
                             {
                                 LastName = u.LastName,
                                 EmailU = u.Email
                             };

但是我的第三个 where 条件不正确,因为 UserProfiles Table 和类别 Table 通过第三个 Table 连接并且 table 没有模型 class 因为其中的两列都是外键。

这是我在上下文中定义的关系 class :

modelBuilder.Entity<Categories>()
            .HasMany(c => c.CategoriesUserProfile).WithMany(x => x.UserProfileCategories).Map(q => q.MapLeftKey("CategoryID").MapRightKey("UserProfileID").ToTable("UserProfileCategories"));

我应该如何选择属于特定类别的用户的电子邮件 ID。

提前致谢。 当然, 这些是我的模型:

public class UserProfiles
{
    public int UserProfileID { get; set; }
    public string LastName { get; set; }
    public bool AnExpert { get; set; }
    public bool AnInstitute { get; set; }
    public bool Client { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Categories> UserProfileCategories{get;set;}
}
public class Categories
{
    public int CategoryID { get; set; }
    public String Name { get; set; }
    public virtual ICollection<UserProfiles> CategoriesUserProfile { get; set; }
    public virtual ICollection<MailStatusTables> CategoriesMailStatusTable { get; set; }

}
public class MailStatusTables
{
    public int MailStatusID { get; set; }
    public bool MailStatus { get; set; }
    public int EnquiryID { get; set; }
    public int CategoryID { get; set; }
    public virtual Categories MailStatusCategory { get; set; }

}

编写 LINQ 查询时,大多数情况下最好从您希望查询的实体开始 return(或包含您希望 [=21] 的 属性 的实体=]).所以,在这种情况下,UserProfile:

var email_list = from u in mcontext.UserProfiles
                 where u.AnExpert
                    && u.AnInstitute
                    && u.UserProfileCategories
                        .Any(c => c.MailStatusTables
                                   .Any(ms => !ms.MailStatus))
                 select new
                 {
                     LastName = u.LastName,
                     EmailU = u.Email
                 };

这将 return 您所有来自至少一个类别包含至少一种 non-mail 状态的用户的所有用户数据。

顺便说一句,我更喜欢 属性 名称,例如 IsExpertHasMailStatus,因为这些名称表示它们是布尔值。