Skip to content

Display the data of parent table using data of child table

Ramsès Zogning II

Asked Nov 10, 2015, 9:02 AM EST1 answer
Share
LinkedInX
Subject : How to display the data of the parent table using the data in the child table in asp.net MVC 4
 
Hello,
 
I am trying to make a web application in C # Asp.net mcv 4.
I'm at the level where I would have to show data of a table "Notifications" based on the data in a table "ReadNotifs".
 
To illustrate the problem, here are more details:
 
I have two tables in my database: Notifications and ReadNotifs.
 
Table : Notifications 
 NotificationID int
 description string
 UserId  int
  
Table : ReadNotifs
 ReadNotifID int
 userid int
 NotificationID int
 
- These are the related models :
 
C#
         public class Notification
         {
                  public Notification()
                  {
                            this.ReplyNotifs = new HashSet<ReplyNotif>();
                  }


                  [Key]
                  public int NotificationID { get; set; }
 
      [Display(Name = "Comment")]
C#
                  public string description { get; set; }


                  public int UserId { get; set; }

                  public virtual UserProfile UserProfile { get; set; }


                  public virtual ICollection<ReadNotif> ReadNotifs { get; set; }
        }


        public class ReadNotif
        {
                  [Key]
                  public int ReadNotifID { get; set; }


                  public int userid { get; set; }


                  public int NotificationID { get; set; }
                  public virtual Notification Notification { get; set; }
        }
 
Notifications and ReadNotifs tables are linked by the relationship One to many. So 1 Notification can be read (ReadNotif) several times.
 
I wish I could have this result :
 
Table : Notifications 
 NotificationID description UserId
 1 Post 1 50
 2 Post 2 51
 3 Post 3 52
 4 Post 4 53
 
Table : ReadNotifs 
 ReadNotifID userid NotificationID
 1 50 3
 2 50 1
 
Result that i want to display in my view:
 
Table : Notifications
 NotificationID description UserId
 2 Post 2 51
 4 Post 4 53
 
Remember : I would have to show data in a table "Notifications" based on the data in a table "ReadNotifs".
So, i want to display a Notification when NotificationID(of Notifications) != NotificationID (ReadNotifs).
 
Any idea how I should proceed?
 
Thank you very much.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    I found the solution :
     
    In Controller :
    Code
    List<Notification> unreadNotifications = db.Notifications.Where(n => !db.ReadNotifs.Any(r => r.NotificationID == n.NotificationID));
    Code
    return View(unreadNotifications)
     For the View, we show data with foreach :)
     
    Hope i help someone :) 
    0