0

There is a file: Opinion.cshtml in Views/Home.

@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>

I have file: OpinionViewModel.cs in a ViewModel folder(created).

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

}

Call stack:

[NullReferenceException: Odwołanie do obiektu nie zostało ustawione na wystąpienie obiektu.] ASP._Page_Views_Home_Opinia_cshtml.Execute() in 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& 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& 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(IList1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList1 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.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +36 System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +28 System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncVoid1.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& completedSynchronously) +155

Problem: I want to display the contents and authors(firstName and lastName) of a opinions, but it's error: Object reference not set to an instance of an object. I tried debugging and i saw that 2 collections: authors and opinions don't have any value. What is the reason of this issue and how to resolve it to correctly select data.

Prezes Łukasz
  • 938
  • 1
  • 9
  • 30
  • Action name is Index but the view name is Options.cshtml. Is this a typo? – Wiktor Zychla Sep 19 '15 at 20:05
  • 1
    Try to replace AsEnumerable() with ToList() – Uriil Sep 19 '15 at 20:13
  • 3
    see a bit about this error: [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Grundy Sep 19 '15 at 20:13
  • Can you post stack trace ? – Peter M. Sep 19 '15 at 20:40
  • @Uriil I repleced and I have new error: The entity or complex type 'Aquapark.DAL.Opinion' cannot be constructed in a LINQ to Entities query. – Prezes Łukasz Sep 19 '15 at 21:05
  • 1
    @ŁukaszKorol, try `select o` instead constuct `new Opinion`, and same with `Person` – Grundy Sep 19 '15 at 21:35
  • It just needs to be `IEnumerable opinions = (from o in db.Opinion select o);` You creating a new `Opinion` from the existing `Opinion` but only setting the `Content` property and the `PersonId` property will be the default. And you have not created a join to `Person` so you will never get the `Person.FullName` anyway. You have not shown your `Opinion` model so hard to understand what you really want to do. –  Sep 19 '15 at 23:59
  • @StephenMuecke ok, I update my post. When I change as you suggest I still have NullReferenceException :( – Prezes Łukasz Sep 20 '15 at 09:26
  • 1
    @ŁukaszKorol, I was just pointing out other errors. You need to debug your code to determine what is null (we can't do it for you). And looking at your error message, its referring to a view named `Opinia.cshtml` which is not even related to the code you have shown- the controller method you have show returns `Index.cshtml`) –  Sep 20 '15 at 12:14

2 Answers2

1

Create Opinion and Author view models, then project to these classes and use ToList()

namespace Aquapark.ViewModels
{    

    public class OpinionViewModel
    {
      public class OpinionDTO()
      {
         public string Content {get; set;}
         public DateTime Date {get; set;}
         public string PersonId {get; set;}
      }

      public class PersonDTO()
      {
         public int PersonId { get; set; }       
         public long Pesel { get; set; }       
         public string FirstName { get; set; }    
         public string LastName { get; set; }     
         public DateTime DateOfBirth  { get; set; }
         public string FullName
          {
            get
             {
               return FirstName + " " + LastName;
             }
          }
      }

        public IEnumerable<OpinionDTO> Opinions { get; set; }
        public IEnumerable<PersonDTO> Authors { get; set; }

    }
}

Queries:

    IEnumerable<OpinionDTO> opinions = (from o in db.Opinion
                                     select new OpinionDTO
                                     {
                                         Content = o.Content
                                     }).ToList();
    //var randomOpinions = db.Opinion.Where(a => a.Date >= DateTime.Parse("2015-01-01")).OrderBy(g => Guid.NewGuid()).Take(6).ToList();
    IEnumerable<PersonDTO> authors = (from p in db.Person
                                   join o in db.Opinion
                                   on p.PersonId equals o.PersonId
                                   select new PersonDTO
                                   {
                                       FullName = p.FirstName + p.LastName,
                                   }).ToList();

References:

The entity cannot be constructed in a LINQ to Entities query

What is the effect of AsEnumerable() on a LINQ Entity?

Community
  • 1
  • 1
Hugh
  • 450
  • 3
  • 13
-1

Hmmm.. I guess the problem is really to create a new instance of these forms. The problem is not related to NullReference but Object not set an Instance.

To do so, perform these steps as answered here: Creating a new instance of form1 and change that forms property

Community
  • 1
  • 1
David BS
  • 1,822
  • 1
  • 19
  • 35