2011-04-25 35 views
1

我是C#的大三學生,我無法找到使用搜索的解決方案C#.Net MVC非靜態字段,方法或屬性需要對象引用

我有一個數據庫模型(EDM)

我在模型文件夾中創建了一個類文件:

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); 
     } 
    } 
} 

接下來爲此模型創建了一個控制器:

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名稱 - fotostorageEntities

需要幫助因爲我真的不知道解決方案。

回答

3

您目前正在致電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); 
    } 
+0

Thanks!你沒有幫助過我! – 2011-04-25 20:27:05

0
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); 
     } 
    } 
} 
相關問題