Gbe*_*nga 3 c# repository-pattern asp.net-core
在 ASP.NET Core-6 实体框架中,我使用通用存储库:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我收到这个警告:
此处“_table”不为空通用存储库中可能返回空引用
我该如何解决这个问题?
谢谢
答案在另一个堆栈交换网站上: https: //softwareengineering.stackexchange.com/questions/433387/whats-wrong-with-returning-null
引用
您已启用 C# 的可为空引用类型 (NRT) 功能。这要求您显式指定何时可以返回 null。因此将签名更改为:
public TEntity? Get(Guid id)
{
// Returns a TEntity on find, null on a miss
return _entities.Find(id);
}
Run Code Online (Sandbox Code Playgroud)
并且警告将会消失。
我没有使用该功能,但希望您的代码应该如下所示
public virtual async Task<T?> GetByIdAsync(object id)
{
return await _table.FindAsync(id);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3573 次 |
| 最近记录: |