I got null reference exception when i trying to view data from table for actually logged user - Klient_has_sklep and if that user isnt signed with Sklep table. When i viewing data for user who is signed with Sklep table everything is ok.
I think problem is in Controller with viewModel
This is my controller
public ActionResult Index(int? id)
{
var viewModel = new Klient_has_SklepIndexData();
viewModel.Klients = db.Klients
.OrderBy(i => i.Nazwisko);
UserManager UM = new UserManager();
int idZalogowanego = UM.GetUserID(User.Identity.Name);
ViewBag.idzal = idZalogowanego;
viewModel.Klient_has_Skleps = viewModel.Klients.Where(i => i.SYSUserID == idZalogowanego).Single().Klient_has_Sklep;
return View(viewModel);
}
This is my view
@model Sklepy.Models.ViewModel.Klient_has_SklepIndexData
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@ViewBag.idzal.</h2>
<h2>Twoje zniżki w sklepach</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>asd</th>
</tr>
@if (Model != null)
{
@foreach (var item in Model.Klient_has_Skleps)
{
<tr>
<td>@item.Znizka1</td>
</tr>
}
}
</table>
This is my Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sklepy.Models.DB;
namespace Sklepy.Models.ViewModel
{
public class Klient_has_SklepIndexData
{
public IEnumerable<Klient> Klients { get; set; }
public IEnumerable<Klient_has_Sklep> Klient_has_Skleps {get; set;}
}
}
Klient class code
public partial class Klient
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Klient()
{
this.Klient_has_Sklep = new HashSet<Klient_has_Sklep>();
}
public int KlientID { get; set; }
public int SYSUserID { get; set; }
public string Imię { get; set; }
public string Nazwisko { get; set; }
public string Adres { get; set; }
public string Telefon { get; set; }
public string Email { get; set; }
public virtual SYSUser SYSUser { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Klient_has_Sklep> Klient_has_Sklep { get; set; }
}