Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

one-to-many relationship foreign key count

public class User
{
    [Key]
    public int id { get; set; } //PK

    public string emailAddress { get; set; }

    public List<Task> tasks { get; set; }

}
public class Task
{
    [Key]
    public int id { get; set; } //PK 

    public string name { get; set; }

    //Navigation Properties
    public User user{ get; set; }

    public int userId { get; set; }

}

I’ve got two models above configured following the MSDN tutorial. So how can I properly get the number of tasks associated with a user?

I tried context.users.Where(u => u.emailAddress == email).FirstOrDefaultAsync().tasks.count; but it gives me a null pointer reference on the tasks object.
Then I tried context.tasks.Where(o=>o.user.emailAddress==email).Count() gives me correct number so it works

so I am wondering why the List is a null reference instead of a list with some elements in? thanks for the advice

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try the following query:

var cnt = context.users
   .Where(u => u.emailAddress == email)
   .Select(u => u.tasks.Count())
   .FirstOrDefault();

You have to use LINQ extension Count() instead of List.Count

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading