C# .Net MVC An object reference is required for th

2019-02-20 04:31发布

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.

2条回答
何必那么认真
2楼-- · 2019-02-20 05:04

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);
    }
查看更多
Anthone
3楼-- · 2019-02-20 05:15
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
    {
        PhotosRepository objPhotosRepository = new PhotosRepository();
        //
        // GET: /Photos/
        public ActionResult ViewPhoto(string userid, int photoid)
        {
            photos CurrentPhoto = objPhotosRepository.GetPhotosById(photoid);
            if (CurrentPhoto == null)
                return View("NotFound");
            else
                return View("ViewPhoto", CurrentPhoto);
        }
    }
}
查看更多
登录 后发表回答