【发布时间】:2022-01-14 23:19:54
【问题描述】:
我正在 ASP.NET Core Web API 中实现 Repository 和 UnitOfWork。
我有这个代码:
数据库上下文:
public class DDMDbContext : IdentityDbContext<ApplicationUser>
{
public DDMDbContext(DbContextOptions<DDMDbContext> options)
: base(options) { }
public virtual DbSet<Mandate> Mandates { get; set; }
}
型号如下图:
public abstract class EntityBase
{
[Key]
public int Id { get; set; }
}
public class Mandate : EntityBase
{
public DateTime DueDate { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
IBaseRepository:
public interface IBaseRepository<T> where T : BaseEntity
{
Task<IEnumerable<T>> GetAll();
}
基础存储库:
public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
{
private readonly DDMDbContext _context;
private DbSet<T> _entities;
public BaseRepository(DDMDbContext context)
{
_context = context;
_entities = context.Set<T>();
}
public async Task<IEnumerable<T>> GetAll()
{
var list = await _entities.ToListAsync();
return list;
}
}
最后是 UnitOfWork:
public interface IUnitOfWork : IDisposable
{
IBaseRepository<Mandate> MandateRepository { get; }
void SaveChanges();
Task SaveChangesAsync();
}
工作单元:
public class UnitOfWork : IUnitOfWork
{
private readonly DDMDbContext _context;
public UnitOfWork(DDMDbContext context)
{
_context = context;
}
#region Mandate
private readonly IBaseRepository<Mandate> _mandateRepository;
public IBaseRepository<Mandate> MandateRepository => _mandateRepository ?? new BaseRepository<Mandate>(_context);
# endregion
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
}
}
}
现在的问题是,当我浏览 IUnitOfWork 中的代码时。
我收到了这个警告:
然后我收到这条消息:'UnitOfWork._mandateRepository' 从未分配给。
_mandateRepository在
中突出显示私有只读 IBaseRepository _mandateRepository;
我该如何解决这个问题?
【问题讨论】:
-
消息很清楚,请问您有什么问题?
标签: c# asp.net-core