我将存储库作为模型传递给视图,在视图中,使用存储库向数据库插入一个条目,我可以在数据库中看到该条目,但是当我使用 getFans() 时,应用程序崩溃并出现以下错误:
An unhandled exception occurred while processing the request.
ArgumentNullException: Value cannot be null.
Parameter name: constructor
System.Linq.Expressions.Expression.New(ConstructorInfo constructor, IEnumerable`1 arguments)
错误发生在这一行:return _context.Fans.ToList();
我有这个存储库类:
public class FanBookRepository : IFanBookRepository
{
private ApplicationDbContext _context;
public FanBookRepository(ApplicationDbContext context)
{
_context = context;
}
public ICollection<Fan> getFans()
{
return _context.Fans.ToList<Fan>();
}
public void addFan(Fan fan)
{
_context.Fans.Add(fan);
_context.SaveChanges();
}
}
我有这个名为索引的视图:
@model Shauli_Blog.Models.FanBookRepository
@{
Model.addFan(new Fan("Asaf", "Karavani", System.DateTime.Now, "Male", new DateTime(1996, 10, 7)));
}
@{
var fans = Model.getFans();
foreach (var fan in fans)
{
<h1>@fan.FirstName</h1>
}
}
而这个控制器:
public class FanBookController : Controller
{
IFanBookRepository _repository;
public FanBookController(IFanBookRepository repository)
{
_repository = repository;
}
// GET: /<controller>/
public IActionResult Index()
{
return View(_repository);
}
}