C# .Net MVC An object reference is required for the nonstatic field, method, or property

Evgeniy Labunskiy picture Evgeniy Labunskiy · Apr 25, 2011 · Viewed 8.2k times · Source

I'm a junior in C# and I cant find the solution using search

I have a database model (EDM)

I have a created a class file in models folder:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace photostorage.Models
{
    public class PhotosRepository
    {
        private fotostorageEntities db = new fotostorageEntities();

        public IEnumerable<photos> FindUserPhotos(string userid)
        {
            return from m in db.photos
                   select m;
        }

        public photos GetPhotosById(int photoid)
        {
            return db.photos.SingleOrDefault(d => d.id == photoid);
        }
    }
}

Next one a created a controller to this model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using photostorage.Models;

namespace photostorage.Controllers
{
    public class PhotosController : Controller
    {
        //
        // GET: /Photos/
        public ActionResult ViewPhoto(string userid, int photoid)
        {
            photos CurrentPhoto = PhotosRepository.GetPhotosById(photoid);
            if (CurrentPhoto == null)
                return View("NotFound");
            else
                return View("ViewPhoto", CurrentPhoto);
        }
    }
}

In results i have an error: An object reference is required for the nonstatic field, method, or property photostorage.Models.PhotosRepository.GetPhotosById(int);

Table name in database - photos EDM connectionStrings name - fotostorageEntities

Need help cause I realy dont know the solution.

Answer

Ed Chapel picture Ed Chapel · Apr 25, 2011

You are currently calling GetPhotosById as a static method. You'll need to create the instance of the PhotosRepository.

    public ActionResult ViewPhoto(string userid, int photoid)
    {
        PhotosRepository photosRepository = new PhotosRepository();
        photos CurrentPhoto = photosRepository.GetPhotosById(photoid);
        if (CurrentPhoto == null)
            return View("NotFound");
        else
            return View("ViewPhoto", CurrentPhoto);
    }