[英]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.