ASP.NET 核心 - 通用存储库中可能的空引用 Return
ASP.NET Core - Possible Null Reference Return in Generic Repository
在 ASP.NET Core-6 Entity Framework 中,我正在使用通用存储库:
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);
}
}
我收到这个警告:
'_table' is not null here
Possible Null Reference Return in Generic Repository
我该如何解决?
谢谢
答案在另一个堆栈交换站点上:https://softwareengineering.stackexchange.com/questions/433387/whats-wrong-with-returning-null
引用
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.
我没有使用该功能,但希望您的代码看起来像
public virtual async Task<T?> GetByIdAsync(object id)
{
return await _table.FindAsync(id);
}
在 ASP.NET Core-6 Entity Framework 中,我正在使用通用存储库:
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);
}
}
我收到这个警告:
'_table' is not null here Possible Null Reference Return in Generic Repository
我该如何解决?
谢谢
答案在另一个堆栈交换站点上:https://softwareengineering.stackexchange.com/questions/433387/whats-wrong-with-returning-null
引用
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.
我没有使用该功能,但希望您的代码看起来像
public virtual async Task<T?> GetByIdAsync(object id)
{
return await _table.FindAsync(id);
}