I'm getting a nullreferenceexception in a method of my repository class, when I'm trying to retrieve all records of a model, I've read about this exception and I think I understand it but I don't get why it is happening in my code.
I have this model:
public class Post
{
[Key]
public int Id { get; set; }
public string Title { get; set; } = "";
public string Body { get; set; } = "";
public DateTime? Created { get; set; } = DateTime.Now;
}
this is my context:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options) { }
public DbSet<Post> Posts { get; set; }
}
The method "GetAllPost()" in my repository class:
public async Task<List<Post>> GetAllPost()
{
var listOfPost = _context.Posts;//here is where the exception is thrown
return await listOfPost.ToListAsync();
}
This is my entire Repository Class:
public class Repository : IRepository
{
private readonly AppDbContext _context;
public Repository(AppDbContext context) {
_context = context;
}
public async Task AddPost(Post post)
{
await _context.Posts.AddAsync(post);
await _context.SaveChangesAsync();
}
public async Task<List<Post>> GetAllPost()
{
var listOfPost = _context.Posts;
return await listOfPost.ToListAsync();
}
public async Task<Post> GetPost(int id)
{
return await _context.Posts.FirstOrDefaultAsync(x=> x.Id == id);
}
public async Task RemovePost(Post post)
{
_context.Remove(post);
await _context.SaveChangesAsync();
}
public async Task UpdatePost(Post post)
{
_context.Posts.Update(post);
await _context.SaveChangesAsync();
}
}
and this is my ConfigureService Method(I'm using postgres by the way):
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddEntityFrameworkNpgsql().AddDbContext<AppDbContext>(
x => x.UseNpgsql(
Configuration.GetConnectionString("DefaultConnection")
)
);
services.AddTransient<IRepository, Repository>();
}
I have my database created with migrations and populated