In ASP.NET Core-6 Entity Framework, I am using Generic Repository:
public interface IGenericRepository<T> where T : class
{
Task<T> GetByIdAsync(object id);
}
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private readonly ApplicationDbContext _context;
internal readonly DbSet<T> _table;
public GenericRepository(ApplicationDbContext context)
{
_context = context;
_table = context.Set<T>();
}
public virtual async Task<T> GetByIdAsync(object id)
{
return await _table.FindAsync(id);
}
}
I got this warning:
'_table' is not null here Possible Null Reference Return in Generic Repository
How do I resolve this?
Thank you
CodePudding user response:
The answer is on another stack exchange site: https://softwareengineering.stackexchange.com/questions/433387/whats-wrong-with-returning-null
Quote
You have enabled the nullable reference types (NRT) feature of C#. This requires you to explicitly specify when a null may be returned. So change the signature to:
public TEntity? Get(Guid id)
{
// Returns a TEntity on find, null on a miss
return _entities.Find(id);
}
And the warning will go away.
I'm not using the feature, but expect your code should look like
public virtual async Task<T?> GetByIdAsync(object id)
{
return await _table.FindAsync(id);
}