简体   繁体   English

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

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

Hello i am using in an Asp.net MVC CORE project a repository pattern adapted from here .您好,我在 Asp.net MVC CORE 项目中使用了从这里改编的存储库模式。 while i am using the GetAll() method to make a call to the database works if i try to use当我使用GetAll()方法调用数据库时,如果我尝试使用

T GetSingle(object id);
T GetSingle(Expression<Func<T, bool>> predicate);

like this var model = _repository.GetSingle(x => x.Id == id);像这样var model = _repository.GetSingle(x => x.Id == id);

or like this var model = _repository.GetSingle(id);或者像这个var model = _repository.GetSingle(id);

Model returns Null.模型返回 Null。

in the Razor View if i change from @model IEnumerable<ApplicationUser> which works ok with the GetAll()在 Razor 视图中,如果我从@model IEnumerable<ApplicationUser>更改,它可以与GetAll()

to this @model ApplicationUser i get Null.对于这个@model ApplicationUser我得到了空值。 My controller is like this:我的控制器是这样的:

[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);
}

Here is the declaration of the Repository if it helps:如果有帮助,这是存储库的声明:

public class EntityBaseRepository<T> : IRepository<T> where T : class, new() 

i am wondering why database returns Null with those two methods??我想知道为什么数据库用这两种方法返回 Null ?

these are the methods这些是方法

        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();
        }

Please, try to rewrite your GetSingle method like this:请尝试像这样重写您的 GetSingle 方法:

public T GetSingle(Expression<Func<T, bool>> predicate)
{
    return _context.Set<T>().Where(predicate).FirstOrDefault();
}

It can helps you, but I am not shure.它可以帮助你,但我不知道。 So, using AsEnumerable method is bad practise.因此,使用 AsEnumerable 方法是不好的做法。 When you call it, all data from database will fetched and parsed to objects.当您调用它时,数据库中的所有数据都将被提取并解析为对象。 If you has thousands of rows in database, you give a OutOfMemory exception如果数据库中有数千行,则会给出 OutOfMemory 异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM