-2

I have done this many many times in .net mvc and so this should be very easy.

All I need to do is reference a method that is in a "Helper" folder I have created to clean up my code.

I have this method here in the folder Helpers.

using Microsoft.AspNetCore.Mvc;
using mocHub2.Models;
using mocHub2.Models.Enterprise;
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Threading.Tasks;

namespace mocHub2.Helpers
{
    public class UserIdentity
    {
        private static EnterpriseContext enterpriseDB = new EnterpriseContext();
        private SLGContext db = new SLGContext();

        public List<int> IdentitySearch()
        {
            object newObject = new object();
            bool StoreManagerAccess = false;
            List<int> StoreIdList = new List<int>();
            UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName), IdentityType.SamAccountName, System.Security.Principal.WindowsIdentity.GetCurrent().Name);

            // Check to see if the user is in the Permissions table 
            if (db.Permissions.Any(x => x.Email == user.EmailAddress))
            {
                StoreManagerAccess = true;
                // If exists add StoreId to List<int> StoreIdList
                db.Permissions.Where(x => x.Email == user.EmailAddress).ToList().ForEach(x => { StoreIdList.Add(x.StoreId); });
            }
            var newlist = new HashSet<decimal>();
            var ListFromPermissionsCheck = db.Permissions.Where(x => x.Email == user.EmailAddress).ToList();

            return StoreIdList;
        }
    }
}

I am in another file the EnterpriseController.cs and I am trying to reference this method as so.

        List<int> storeIdList = UserIdentity.IdentitySearch();

There is a red line under UserIdentity.IdentitySearch() and says

object reference required for non static field

I can make my method static but then it gives the same error to the db part in the method.

What do I need to do to reference the method?

JSkyS
  • 413
  • 6
  • 14
  • Does this answer your question? [CS0120: An object reference is required for the nonstatic field, method, or property 'foo'](https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop) – Eugene Podskal Nov 29 '19 at 20:26
  • Yes it did. Thanks Eugene – JSkyS Dec 05 '19 at 17:37

1 Answers1

2

The method IdentitySearch isn't static, so you can't call it like that. You would have make that method static, by using the static keyword.

private static SLGContext db = new SLGContext(); //Because IdentitySearch is using that variable, so it has to be static.

public static List<int> IdentitySearch()
//Here the method body
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92