[英]Calling Repository Pattern methods returns null in Asp.Net Mvc Core
您好,我在 Asp.net MVC CORE 项目中使用了从这里改编的存储库模式。 当我使用GetAll()
方法调用数据库时,如果我尝试使用
T GetSingle(object id);
T GetSingle(Expression<Func<T, bool>> predicate);
像这样var model = _repository.GetSingle(x => x.Id == id);
或者像这个var model = _repository.GetSingle(id);
模型返回 Null。
在 Razor 视图中,如果我从@model IEnumerable<ApplicationUser>
更改,它可以与GetAll()
对于这个@model ApplicationUser
我得到了空值。 我的控制器是这样的:
[HttpGet]
public IActionResult Index(string id)
{
//var model = _repository.GetAll();
var model = _repository.GetSingle(x => x.Id == id);
//var model = _repository.GetSingle(id);
if(model == null)
{
return NotFound();
}
return View(model);
}
如果有帮助,这是存储库的声明:
public class EntityBaseRepository<T> : IRepository<T> where T : class, new()
我想知道为什么数据库用这两种方法返回 Null ?
这些是方法
public T GetSingle(object id)
{
return _context.Set<T>().Find(id);
}
public T GetSingle(Expression<Func<T, bool>> predicate)
{
return _context.Set<T>().FirstOrDefault(predicate);
}
public IEnumerable<T> GetAll()
{
return _context.Set<T>().AsEnumerable();
}
请尝试像这样重写您的 GetSingle 方法:
public T GetSingle(Expression<Func<T, bool>> predicate)
{
return _context.Set<T>().Where(predicate).FirstOrDefault();
}
它可以帮助你,但我不知道。 因此,使用 AsEnumerable 方法是不好的做法。 当您调用它时,数据库中的所有数据都将被提取并解析为对象。 如果数据库中有数千行,则会给出 OutOfMemory 异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.