我在我的專案中使用了 IdentityDbContext。我的資料庫有一些相互連接的表(關系)。我想使用存盤庫模式。我宣告了我所有的介面。然后,我嘗試實施它們。問題是我無法創建 IdentityAppContext 的實體,因為建構式需要一個輸入引數“選項”。我該如何實施它們?
IdentityAppContext.cs :
public class IdentityAppContext: IdentityDbContext<AppUser, AppRole, int>
{
public IdentityAppContext(DbContextOptions<IdentityAppContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<AppUser> Users { get; set; }
public DbSet<Message> Messages { get; set; }
public DbSet<PM> PMs { get; set; }
public DbSet<Notification> Notifications { get; set; }
public DbSet<FileRepository> Files { get; set; }
}
IPmRepository.cs :
public interface IPmRepository
{
IEnumerable<PM> GetAllPMs();
PM GetPmById(int pmId);
bool InsertPM(PM pm);
bool UpdatePM(PM pm);
bool DeletePM(int pmId);
bool DeletePM(PM pm);
void Save();
}
PmRepository.cs :
public class PmRepository : IPmRepository
{
IdentityAppContext db = new IdentityAppContext();
public IEnumerable<PM> GetAllPMs()
{
}
public PM GetPmById(int pmId)
{
throw new NotImplementedException();
}
public bool InsertPM(PM pm)
{
throw new NotImplementedException();
}
public bool UpdatePM(PM pm)
{
throw new NotImplementedException();
}
public bool DeletePM(int pmId)
{
throw new NotImplementedException();
}
public bool DeletePM(PM pm)
{
throw new NotImplementedException();
}
public void Save()
{
throw new NotImplementedException();
}
}
uj5u.com熱心網友回復:
假設 DbContext 已注冊到 Startup.cs 檔案中的 DI 容器,使用如下內容:
services.AddDbContext<IdentityAppContext>(opt =>
{
opts.UseSqlServer(myConnectionString);
})
然后以與上述相同的方法添加以下內容將在同一個 DI 容器中注冊您的存盤庫:
services.AddScoped<IPmRepository, PmRepository>();
然后在您的存盤庫中:
public class PmRepository : IPmRepository
{
readonly IdentityAppContext _context;
// 'context' parameter is automagically provided by the container.
public PmRepository(IdentityAppContect context)
{
_context = context;
}
public bool InsertPM(PM pm)
{
_context.PMs.Add(pm);
}
}
然后,在您的控制器(也由容器提供)中,您應該能夠在建構式中從容器請求一個 IPmRepository:
public class MyController : Controller
{
readonly IdentityAppContext _context;
readonly IPmRepository _pmRepository;
// Both 'context' and 'pmRepository' are automagically provided by the container
public MyController(
IdentityAppContext context,
IPmRepository pmRepository)
{
_context = context;
_pmRepository = pmRepository;
}
[HttpPost]
public async Task DoSomething(MyRequest request)
{
_pmRepository.InsertPM(new PM() { Id = request.Id });
await _context.SaveChangesAsync();
}
}
注意,因為 IdentityAppContext 和 IPmRepository 和 MyController 注冊在同一個容器中,所以框架可以自動為 MyController 建構式提供引數。
此外,當為控制器創建 PmRepository 時,容器可以查看 PmRepository 的建構式引數并看到它需要一個 IdentityAppContext,它可以自動提供,因為它注冊在同一個容器中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/375272.html
標籤:C# asp.net-mvc 实体框架核心 存储库模式
上一篇:單擊側邊選單項時如何避免重繪頁面
