Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ASP.NET Core – Possible Null Reference Return in Generic Repository

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How do I resolve this?

Thank you

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading