使用Lambda表达式或理解语法的子查询

时间:2017-03-13 15:46:36

标签: c# sql-server entity-framework lambda

我是MVC和EF的新手。我正在遵循Database First方法。我在我的数据库中有2个名为tblSubject和tblPrerequisite的表。我使用EF将它们映射到我的应用程序。这是两张图的图片: enter image description here

enter image description here 现在我需要执行一个如下所示的查询:

select Sc from tblSubject where Sc not in (Select Prerequisite from tblPrerequisite where Sc = @subjectCode) and Sc != @subjectCode

此查询应该检索尚未被指定为我作为参数传递的主题的先决条件的所有主题。第二个条件应该是过滤掉主体本身 - 因为它满足第一个条件 - 。我需要知道如何使用Lambda Expression或Comprehension Syntax来完成它。如果可以,请帮助

编辑:这是我映射的主题类的代码

 public partial class Subject
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Subject()
    {
        this.tblSubjectScores = new HashSet<SubjectScore>();
        this.Prerequisite = new HashSet<Subject>();
        this.IsPrerequisiteFor = new HashSet<Subject>();
        this.tblSubject_Program = new HashSet<Subject_Program>();
    }

    public string Sc { get; set; }
    public string Name_EN { get; set; }
    public string Name_AR { get; set; }
    public byte CCH { get; set; }
    public string Description { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<SubjectScore> tblSubjectScores { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Subject> Prerequisite { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Subject> IsPrerequisiteFor { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Subject_Program> tblSubject_Program { get; set; }
}

这是我用于测试的行动方法

 public ActionResult Index()
    {
        Subject s = db.Subjects.FirstOrDefault(x => x.Sc == "Acc102");
        var notYetAssigned = db.Subjects.Where(x => s.Prerequisite.Any(y=> y.Sc == s.Sc && y.Sc!=x.Sc) && x.Sc != s.Sc).ToList();
        return View(notYetAssigned);
    }

1 个答案:

答案 0 :(得分:0)

我不完全确定我会按照你的要求行事,但这是我的尝试:

<MainScreenTopList />

请参阅工作小提琴here