Home > Net >  one-to-many relationship foreign key count
one-to-many relationship foreign key count

Time:02-03

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

CodePudding user response:

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

CodePudding user response:

I think you are using entity framework with Eager loading (description). In that case you should call explicitly Include() method to load all user tasks. Example:

await (context.users.Where(u => u.emailAddress == email).Include(u => u.Tasks).FirstOrDefaultAsync()).Tasks.Count();

UPD: Not for the Production

  •  Tags:  
  • Related