0

我将存储库作为模型传递给视图,在视图中,使用存储库向数据库插入一个条目,我可以在数据库中看到该条目,但是当我使用 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);
    }
}
4

1 回答 1

0

将存储库传递给视图是错误的做法。创建一个类,这将是视图的视图模型,它接收粉丝列表。

public class IndexViewModel
{
    public IList<Fan> Fans { get; set; }
}

public IActionResult Index()
{
    var viewModel = new IndexViewModel();

    viewModel.Fans = _repository.getFans();

    return View(viewModel);
}

这个想法是您通过使用视图模型将视图中使用的数据与该数据的源分开。这样,如果粉丝列表来自另一个来源,比如一个数组而不是 from _repoistory,那么它与视图无关,因为不需要更改。这一切都是为了减少视图和数据源之间的凝聚力。

回到您的问题,提出异常

_context.Fans.ToList();

你确定那_context.Fans不是NULL吗?也许您应该将功能更改为

return _context.Fans != null ? _context.Fans.ToList() : Enumerable.Empty<Fan>().ToList();

于 2016-05-16T14:38:20.707 回答