C#.Net MVC非静态字段,方法或属性需要对象引用
我是C#的大三学生,我无法使用搜索找到解决方案
我有一个数据库模型(EDM)
我在models文件夹中创建了一个类文件:
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 FindUserPhotos(string userid) { return from m in db.photos select m; } public photos GetPhotosById(int photoid) { return db.photos.SingleOrDefault(d => d.id == photoid); } } }
接下来,为此模型创建了一个控制器:
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); } } }
在结果中我有一个错误:非静态字段,方法或属性photostorage.Models.PhotosRepository.GetPhotosById(int);
数据库中的表名 – 照片EDM connectionStrings name – fotostorageEntities
需要帮助因为我真的不知道解决方案。
您目前正在调用GetPhotosById
作为静态方法。 您需要创建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); }
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); } } }