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