我在MVC4中创建了一个新项目。我收到此错误:
System.ArgumentNullException: Value can not be null.
Parameter name: source.
数据库存在,表存在并填充数据。
任何提示?
Controler ShopController.cs
...
SQLEntities DB = new SQLEntities();
public ActionResult Index()
{
var x = DB.Types.ToList(); <-Here I get an exception
return View(x);
}
...
模型 Type.cs
using System.Collections.Generic;
namespace xxx.Models
{
public class Type
{
public int TypeId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
模型 SQLEntities.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace xxx.Models
{
public class SQLEntities
{
public DbSet<Type> Types { get; set; }
}
}
的Web.config
<connectionStrings>
<add name="SQLEntities" connectionString="Data Source=KOMPUTER\SQLEXPRESS;Initial Catalog=myDB;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
编译器不指示任何错误。只有当他想要mypage/Shop
获得例外时才会这样。
堆栈跟踪
{System.ArgumentNullException: Value can not be null.
Parameter name: source.
w System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
w Print.Controllers.StoreController.Index() w c:\Users\John\Documents\Visual Studio 2013\Projects\Print\Print\Controllers\StoreController.cs:wiersz 18
w lambda_method(Closure , ControllerBase , Object[] )
w System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
w System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
w System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
w System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
w System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
w System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
w System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
w System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
w System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()}
答案 0 :(得分:3)
您的问题是SQLEntities
应该继承自DbContext
。
您的问题是SQLEntities.Types
显然为空。您不应该被要求初始化此属性,因为当所有内容都正确设置时,EntityFramework会自动执行此属性。
将您的代码更改为:
public class SQLEntities: DbContext
{
public DbSet<Type> Types { get; set; }
}