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

asp.net-core asp.net-mvc c# entity-framework-core repository-pattern

Question

Hello i am using in an Asp.net MVC CORE project a repository pattern adapted from here. while i am using the GetAll() method to make a call to the database works if i try to use

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

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

or like this var model = _repository.GetSingle(id);

Model returns Null.

in the Razor View if i change from @model IEnumerable<ApplicationUser> which works ok with the GetAll()

to this @model ApplicationUser i get Null. 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??

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

1
0
12/9/2019 5:58:27 PM

Accepted Answer

Please, try to rewrite your GetSingle method like this:

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. 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

1
12/9/2019 6:06:36 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow