在 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' 在此處不為空 通用存盤庫中可能回傳空參考
我該如何解決這個問題?
謝謝
uj5u.com熱心網友回復:
答案在另一個堆疊交換站點: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);
}
警告將消失。
我沒有使用該功能,但希望您的代碼看起來像
public virtual async Task<T?> GetByIdAsync(object id)
{
return await _table.FindAsync(id);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431761.html
