0

I'm learning ASP from Pro Asp.Net MVC5, when i added a second db and class to the solution i get bug whenever i add DbSet in EFDbContext while loading customer or product page.

Note: product page is working fine, once i delete/move DbSet from EFDbContext and i checked What is a NullReferenceException and how do I fix it

EFDbContext.cs

using SportsStore.Domain.Entities;
namespace SportsStore.Domain.Concrete 
{
   public class EFDbContext : DbContext
   {
      public DbSet<Product> Products { get; set; }

      **public DbSet<Customer> Customers{ get; set; }**
   }
}

EFProductRepostory.cs

namespace SportsStore.Domain.Concrete 
{
   public class EFProductRepository : IProductRepository 
   {
       private EFDbContext context = new EFDbContext();

       public IEnumerable<Product> Products 
       {
          get { return context.Products; }
       }

       public IEnumerable<Customer> Customers
       {
           get { return context.Customers; }
       }
}

NinjectDependencyResolver.cs

private void AddBindings()
{
    kernel.Bind<IProductRepository>().To<EFProductRepository>();
}

Web.config:

<connectionStrings>
    <add name="EFDbContext" connectionString="Data Source=(localdb)\v11.0;Initial
        Catalog=SportsStore;Integrated Security=True"
        providerName="System.Data.SqlClient"/>
</connectionStrings>

Error:

System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=System.Web
  StackTrace:
       at System.Web.UI.ParseChildrenAttribute.GetHashCode()
       at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
       at System.Collections.Generic.HashSet`1.InternalGetHashCode(T item)
       at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
       at System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1 other)
       at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer)
       at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection)
       at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(Type type)
       at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.<>c__DisplayClass4.<GetAttributes>b__3(PropertyInfo pi)
       at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
       at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo propertyInfo)
       at System.Data.Entity.ModelConfiguration.Conventions.PropertyAttributeConfigurationConvention`1.<.ctor>b__0(ConventionTypeConfiguration ec)
       at System.Data.Entity.ModelConfiguration.Conventions.TypeConvention.ApplyCore(Type memberInfo, ModelConfiguration modelConfiguration)
       at System.Data.Entity.ModelConfiguration.Conventions.TypeConventionBase.Apply(Type memberInfo, ModelConfiguration modelConfiguration)
       at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
       at System.Data.Entity.ModelConfiguration.Conventions.Convention.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
       at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
       at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapComplexType(Type type, Boolean discoverNested)
       at System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapPrimitiveOrComplexOrEnumProperty(PropertyInfo propertyInfo, Func`1 structuralTypeConfiguration, Boolean discoverComplexTypes)
       at System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapIfNotNavigationProperty(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
       at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<>c__DisplayClass14.<MapEntityType>b__e(PropertyMapper m, PropertyInfo p)
       at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapStructuralElements[TStructuralTypeConfiguration](Type type, ICollection`1 annotations, Action`2 propertyMappingAction, Boolean mapDeclaredPropertiesOnly, Func`1 structuralTypeConfiguration)
       at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
       at System.Data.Entity.ModelConfiguration.Mappers.NavigationPropertyMapper.Map(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
       at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
       at System.Data.Entity.DbModelBuilder.<>c__DisplayClassd.<MapTypes>b__7(Type type)
       at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
       at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
       at System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model)
       at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
       at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
       at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
       at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
       at System.Data.Entity.Internal.InternalContext.Initialize()
       at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
       at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
       at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
       at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
       at ASP._Page_Views_admin_Admin_cshtml.Execute() in c:\Visual Studio 2013\Projects\Store\SportsStore.WebUI\Views\Admin\Index.cshtml:line 46
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
       at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
       at System.Web.WebPages.StartPage.RunPage()
       at System.Web.WebPages.StartPage.ExecutePageHierarchy()
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
       at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
       at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
       at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)

Update: One last thing to explain. When i moved public DbSet Customers{ get; set; } into another class the admin page loads normally, so repository.Products doesn't return null, i don't know why that happens

Source Error:
Line 44:             </tr>
Line 45: 
Line 46:             @foreach (var item in Model)
Line 47:             {
Line 48:                 <tr>

Admin/index.cshtml:

@foreach (var item in Model)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.Name)</td>
        <td>@Html.DisplayFor(modelItem => item.Description)</td>
        <td>@Html.DisplayFor(modelItem => item.Price)</td>
        <td>@Html.DisplayFor(modelItem => item.Category)</td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ProductID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ProductID })
        </td>
    </tr>
}

AdminController.cs

namespace SportsStore.WebUI.Controllers
{
    public class AdminController : Controller
    {
        private IProductRepository repository;

        public AdminController(IProductRepository repo)
        {
            repository = repo;
        }

        public ViewResult Index()
        {
            return View(repository.Products);
        }
    }
}
Community
  • 1
  • 1
ma1169
  • 659
  • 1
  • 8
  • 26
  • 2
    Welcome to SO. Please show the line of code that triggers the exception. – Keith Payne Sep 24 '14 at 00:35
  • 1
    You didn't show code from your controller but my guess is you did not pass a Model to the view from your controller. – Tony Sep 24 '14 at 19:47
  • i did passed Model, this page works fine if i deleted DbSet Customers{ get; set; } but when i add it repository.Products return null, – ma1169 Sep 24 '14 at 19:53
  • Note to closers: this is not a duplicate of the canonical NullReferenceException question. At the worst, it might be a new case that should be added to the answers to that question. – John Saunders Sep 24 '14 at 19:56
  • 1
    This may be a silly question, but do you have a Customers table in your database? When you step through the code, is it the IProductRepository in the controller that is the null reference, or is it the DbSet causing the error? – Eric King Sep 24 '14 at 20:17
  • Yes i have customer table in db with data. it is IProductRepository that return null, when i move DbSet , IProductRepository doesn't return null idk why – ma1169 Sep 24 '14 at 20:20
  • i solved it. one of the attributes i have in the customer db had a null value. Once i filled it with value everything works fine again – ma1169 Sep 25 '14 at 01:39

1 Answers1

1

The error was result of having one attribute with null value

------------------------------------
| FNAME | LNAME | ........| AVATAR |
------------------------------------
| xxxxx | xxxxx | xxxxxxx |  NULL  |
------------------------------------

filling Avatar with value seems to solve it, i never suspected that because there was already some data in the rest of the field

ma1169
  • 659
  • 1
  • 8
  • 26