0

I'm filtering Contact_data by the user's permission e.i super_admins can pull all Contact_data and normal_users can only pull their own Contact_data.

this is my query:

var contacts= db.Contacts.Where(x => x.Contact != null); // unfilteres & returns all contacts
int UserId = Convert.ToInt32(Session["UserId"].ToString()); // returns the logged-in user id

          if (user.Role.Name != "Super Administrator")
            {
                contacts= db.Contacts.Where(x => x.CreatedBy == UserId); //CreatedBy is type int
            }
            else
            {
                 contacts= db.Contacts.Where(x => x.Contact != null);
            }

I get the error: Object reference not set to an instance of an object. //if (user.Role.Name != "Super Administrator")

What am I doing wrong?

yopipe
  • 1
  • 4
  • You may need to include roles in your linq that gets the users – garethb Nov 12 '20 at 11:43
  • @garethb, I'm sorry, I don't understand? – yopipe Nov 12 '20 at 11:47
  • 1
    The Role property is null, if you are getting the user from the db before this call make sure you include the Role as part of the query, something like: db.Users.Include(x=>x.Role).Where(x=>x.Id = 1).First() the .Include will also load in memory the role (if it has one) – dariogriffo Nov 12 '20 at 11:50
  • @dariogriffo that makes sense! thanks!! – yopipe Nov 12 '20 at 11:53

0 Answers0