【问题标题】:C# .Net MVC An object reference is required for the nonstatic field, method, or propertyC# .Net MVC 非静态字段、方法或属性需要对象引用
【发布时间】:2011-08-12 13:43:21
【问题描述】:

我是 C# 的大三学生,我无法使用搜索找到解决方案

我有一个数据库模型 (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 连接字符串名称 - fotostorageEntities

需要帮助,因为我真的不知道解决方案。

【问题讨论】:

    标签: c# asp.net-mvc ado.net-entity-data-model datamodel


    【解决方案1】:

    您当前正在调用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);
        }
    

    【讨论】:

    • 谢谢!你的回答帮助了我!
    【解决方案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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多