【发布时间】:2022-01-10 00:32:29
【问题描述】:
我在我的项目中使用了 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();
}
}
【问题讨论】:
-
为什么你认为你需要使用存储库模式? DbSet 已经是一个单实体存储库。 DbContext 已经是一个多实体的工作单元。
GetAllPMs方法很少有用 - 很少有任何理由加载表中的所有行,除非您想填充查找表。在像 ORM 这样的高级抽象上使用低级“存储库”接口实际上是一种反模式 -
与@PanagiotisKanavos 一致,避免使用反模式。这将帮助您在处理 IdentityDbContext 时进行设置:stackoverflow.com/questions/50377705/…,可能重复:stackoverflow.com/questions/23226140/…
-
如果您想使用 DDD,请注意 DDD 使用存储库作为 聚合根 - 这是您需要加载以处理特定用途的对象图的根案例(DDD 术语中的有界上下文)。 不 单个实体。在这种情况下,是的,specialized Repository 是有意义的。在那个级别,绝对不需要具有 CRUD 方法的类,不需要加载表中的所有对象。
-
至于
IdentityDbContext为什么不能和new一起使用,那是因为它是用来和依赖注入一起使用的。使用该 DbContext 的类需要以相同的方式工作 - 而不是尝试手动创建它们的依赖项,而是接受它们作为构造函数参数。只需更改AddDbContext中注册的选项或传递给构造函数的选项,就可以轻松地将底层存储从 SQL Server 更改为 MySQL 再到 Oracle 到 NoSQL 数据库。这样可以轻松进行单元测试 - 您可以使用内存提供程序,而无需修改 DbContext 或任何使用它的代码 -
假设你真的定义了一个
PmRepository,它需要一个接受IdentityAppContext参数的构造函数。
标签: c# asp.net-mvc entity-framework-core repository-pattern