在 Asp.Net Mvc Core 中调用存储库模式方法 returns null

Calling Repository Pattern methods returns null in Asp.Net Mvc Core

你好,我在 Asp.net MVC 核心项目中使用了一个改编自 here 的存储库模式。 当我使用 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);

型号returns空。

在 Razor 视图中,如果我从 @model IEnumerable<ApplicationUser> 更改,它可以与 GetAll()

配合使用

对于这个 @model ApplicationUser 我得到 Null。 我的控制器是这样的:

[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() 

我想知道为什么数据库 returns 使用这两种方法为空??

这些是方法

        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 异常