问题
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.
回答1:
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);
}
回答2:
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);
}
}
}
来源:https://stackoverflow.com/questions/5782783/c-sharp-net-mvc-an-object-reference-is-required-for-the-nonstatic-field-method