本文介绍了C#.Net MVC非静态字段,方法或属性需要对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm a junior in C# and I cant find the solution using search

我有一个数据库模型(EDM)

I have a database model (EDM)

我在models文件夹中创建了一个类文件:

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

结果是我有一个错误:非静态字段,方法或属性phototorage.Models.PhotosRepository.GetPhotosById(int);需要对象引用

In results i have an error: An object reference is required for the nonstatic field, method, or property photostorage.Models.PhotosRepository.GetPhotosById(int);

数据库中的表名-照片EDM connectionStrings名称-fotostorageEntities

Table name in database - photosEDM connectionStrings name - fotostorageEntities

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

Need help cause I realy dont know the solution.

推荐答案

您当前正在以静态方法调用GetPhotosById.您需要创建PhotosRepository的实例.

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

这篇关于C#.Net MVC非静态字段,方法或属性需要对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:47