【发布时间】:2014-11-18 08:16:28
【问题描述】:
我正在从 Pro Asp.Net MVC5 学习 ASP,当我向解决方案添加第二个数据库和类时,每当我在加载客户或产品页面时在 EFDbContext 中添加 DbSet 时都会遇到错误。
注意:产品页面工作正常,一旦我从 EFDbContext 中删除/移动 DbSet 并检查了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>
错误:
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)
更新: 最后一件事要解释。当我移动公共 DbSet 客户{ get;放; } 进入另一个类,管理页面正常加载,所以 repository.Products 不返回 null,我不知道为什么会发生这种情况
Source Error:
Line 44: </tr>
Line 45:
Line 46: @foreach (var item in Model)
Line 47: {
Line 48: <tr>
管理员/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);
}
}
}
【问题讨论】:
-
欢迎来到 SO。请显示触发异常的代码行。
-
您没有显示控制器中的代码,但我猜您没有将模型从控制器传递给视图。
-
我确实通过了模型,如果我删除了 DbSet
Customers{ get; 这个页面可以正常工作放; } 但是当我添加它时 repository.Products 返回 null, -
关闭者注意:这不是规范 NullReferenceException 问题的重复。在最坏的情况下,这可能是一个新案例,应该添加到该问题的答案中。
-
这可能是一个愚蠢的问题,但是您的数据库中有客户表吗?当您单步执行代码时,是控制器中的 IProductRepository 是空引用,还是 DbSet
导致错误?
标签: c# asp.net-mvc asp.net-mvc-5