programmer
programmer

Reputation: 49

Filter By Id in asp.net mvc

I get problem with filter data when i using where condition the data not show in the table or page.

I have three tables Groups , Subgroups , Students

First i select the group then i select subgroup and from subgroup students table show

this is my controller:

public ActionResult Index(int? id)
{
    var students = db.Students.AsQueryable()
        .Include(s => s.Groups)
        .Include(s => s.Subgroups)
        .Include(s => s.Schedules)
        .Include(s => s.Teachers);

    if (id != null)
    {
        students = students
            .Where(s => s.SubgroupId == id).Where(s => s.GroupId == id);
    }

    ViewBag.result = students;
    return View(students.ToList());
}

Group Class:

public class Group
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Subgroup Class:

public class Subgroup
{
    public int Id { get; set; }  
    public string Name { get; set; }
    [ForeignKey("GroupId")]
    public virtual Group Group { get; set; }
    public int? GroupId { get; set; }
}

Student class:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    [ForeignKey("GroupId")]
    public virtual Group Groups { get; set; }
    public int? GroupId { get; set; }
    [ForeignKey("SubgroupId")]
    public virtual Subgroup Subgroups { get; set; }
    public int? SubgroupId { get; set; }
}

when i delete groupId the data show but the group data not filter so all group show .

I do not know what is the mistake

Thank you

Upvotes: 0

Views: 924

Answers (1)

Fourat
Fourat

Reputation: 2447

You're filtering twice, try filtering once :

if (id != null)
{
    students = students
        .Where(s => s.SubgroupId == id && s.GroupId == id);
}

Also, if in your model/app the Student can belong to a group and a subgroup whose group is different from the student's group (which is very likely) then you need to remove the Group foreign key/property from the Student entity because you can always access the Group from the Subgroup property.

Upvotes: 2

Related Questions