如何设置对象的实例?

时间:2015-09-19 19:57:32

标签: c# .net asp.net-mvc

在Views / Home中有一个文件: Opinion.cshtml

@model Aquapark.ViewModels.OpinionViewModel
@{
    ViewBag.Title = "Opinia";
    Layout = "~/Views/Shared/_StoreLayout.cshtml";
}

<h2>Opinia</h2>
<div style="margin-top: 20px; line-height: 22px;">
    <div class="opinion-box">
        @foreach (var opinions in Model.Opinions)
        {
            <div class="opinion-box-content">
                <div class="opinion-box-content-inside">@opinions.Content</div>
                <div class="date">@opinions.Date</div>
            </div>
            <div class="opinion-author">@opinions.PersonId</div>
        }
    </div>
</div>

我在 ViewModel 文件夹(已创建)中有文件: OpinionViewModel.cs

using Aquapark.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Aquapark.ViewModels
{
    public class OpinionViewModel
    {
        public IEnumerable<Opinion> Opinions { get; set; }
        public IEnumerable<Person> Authors { get; set; }
    }
}

Person.cs

namespace Aquapark.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Person")]
    public partial class Person
    {
        [Key]
        public int PersonId { get; set; }

        [Required]
        public long Pesel { get; set; }

        [Required]
        [StringLength(30, ErrorMessage = "Imię nie może zawierać więcej niż 30 znaków.")]
        [Display(Name = "Imię")]
        public string FirstName { get; set; }

        [Required]
        [StringLength(60, ErrorMessage = "Nazwisko nie może zawierać wiecej niż 60 znaków.")]
        [Display(Name = "Nazwisko")]
        public string LastName { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{dd/mm/yyyy}", ApplyFormatInEditMode = true)]
        [Display(Name = "Data urodzenia")]
        public DateTime DateOfBirth  { get; set; }

        public virtual Client Client { get; set; }

        public virtual Employee Employee { get; set; }

        public string FullName
        {
            get
            {
                return FirstName + " " + LastName;
            }
        }
    }
}

HomeController.cs

 public class HomeController : Controller
{
    private AquaparkContext db = new AquaparkContext();
    // GET: Home
    public ActionResult Index()
    {
        IEnumerable<Opinion> opinions = (from o in db.Opinion
                                         select new Opinion
                                         {
                                             Content = o.Content
                                         }).AsEnumerable();
        //var randomOpinions = db.Opinion.Where(a => a.Date >= DateTime.Parse("2015-01-01")).OrderBy(g => Guid.NewGuid()).Take(6).ToList();
        IEnumerable<Person> authors = (from p in db.Person
                                       join o in db.Opinion
                                       on p.PersonId equals o.PersonId
                                       select new Person
                                       {
                                           FullName = p.FirstName + p.LastName,
                                       }).AsEnumerable();

        var vm = new OpinionViewModel()
        {
            Opinions = opinions,
            Authors = authors,
        };
        return View(vm);
    }

Opinion.cs

public class Opinion
{
    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int OpinionId { get; set; }

    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int PersonId { get; set; }
    [Required]
    [StringLength(60, ErrorMessage = "Treść nie może zawierać więcej niż 40 znaków.")]
    [Display(Name = "Treść")]
    public string Content { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{dd/mm/yyyy}", ApplyFormatInEditMode = true)]
    [Display(Name = "Data wystawienia")]
    public DateTime Date { get; set; }
    public virtual Client Client { get; set; }

}

调用堆栈:

  

[NullReferenceException:Odwołaniedoobiektuniezostałaustawionenawystąpienieobiektu。]          ASP._Page_Views_Home_Opinia_cshtml.Execute()在c:\ Users \ Asus N551 \ OneDrive \ Documents \ Aquapark \ Aquapark \ Views \ Home \ Opinia.cshtml:10          System.Web.WebPages.WebPageBase.ExecutePageHierarchy()+198          System.Web.Mvc.WebViewPage.ExecutePageHierarchy()+ 105          System.Web.WebPages.StartPage.RunPage()+17          System.Web.WebPages.StartPage.ExecutePageHierarchy()+64          System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,TextWriter writer,WebPageRenderingBase startPage)+78          System.Web.Mvc.RazorView.RenderView(ViewContext viewContext,TextWriter writer,Object instance)+235          System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext,TextWriter writer)+107          Castle.Proxies.Invocations.IView_Render.InvokeMethodOnTarget()+118          Castle.DynamicProxy.AbstractInvocation.Proceed()+80          Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed()+11          Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action)+76          Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context,TimerResult&amp; timerResult)+135          Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context)+25          Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation)+84          Castle.DynamicProxy.AbstractInvocation.Proceed()+108          Castle.Proxies.IViewProxy.Render(ViewContext viewContext,TextWriter writer)+214          System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)+291          Castle.Proxies.AsyncControllerActionInvokerProxy.InvokeActionResult_callback(ControllerContext controllerContext,ActionResult actionResult)+13          Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionResult.InvokeMethodOnTarget()+113          Castle.DynamicProxy.AbstractInvocation.Proceed()+80          Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed()+11          Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action)+76          Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context,TimerResult&amp; timerResult)+135          Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context)+25          Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation)+84          Castle.DynamicProxy.AbstractInvocation.Proceed()+108          Castle.Proxies.AsyncControllerActionInvokerProxy.InvokeActionResult(ControllerContext controllerContext,ActionResult actionResult)+202          System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList 1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList 1个过滤器,Int32 filterIndex,ResultExecutingContext preContext,ControllerContext controllerContext,ActionResult actionResult)+420          System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext,IList 1 filters, ActionResult actionResult) +52 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult 1.CallEndDelegate(IAsyncResult asyncResult)+10          System.Web.Mvc.Async.WrappedAsyncResultBase 1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13 System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult)+36          System.Web.Mvc.Async.WrappedAsyncResultBase 1.End() +54 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12 System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult)+28          System.Web.Mvc.Async.WrappedAsyncResultBase 1.End() +54 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21 System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult)+36          System.Web.Mvc.Async.WrappedAsyncResultBase`1.End()+54          System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)+31          System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)+9          System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+9651688          System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+155

问题: 我想显示意见的内容和作者(firstName和lastName),但它是错误的:对象引用未设置为对象的实例。我试过调试,我看到2个集合:作者意见没有任何价值。这个问题的原因是什么以及如何解决它以正确选择数据。

0 个答案:

没有答案