我在存储库类的一个方法中遇到了一个空引用异常,当我试图检索模型的所有记录时,我读过这个异常,我认为我理解它,但我不明白为什么它会在我的代码中发生。
我有这个模型:
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;
}
这是我的背景:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options) { }
public DbSet<Post> Posts { get; set; }
}
我的存储库类中的方法“GetAllPost()”:
public async Task<List<Post>> GetAllPost()
{
var listOfPost = _context.Posts;//here is where the exception is thrown
return await listOfPost.ToListAsync();
}
这是我的整个存储库类:
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();
}
}
这是我的ConfigureService方法(顺便说一句,我使用的是postgres):
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddEntityFrameworkNpgsql().AddDbContext<AppDbContext>(
x => x.UseNpgsql(
Configuration.GetConnectionString("DefaultConnection")
)
);
services.AddTransient<IRepository, Repository>();
}
我已通过迁移创建并填充了数据库