我最近开始使用 OAuth 并正在遵循此教程。
我使用 ASP.NET Identity 自动生成的表(我没有创建自己的
DbSet<User>
)。现在我需要让我的 UserRepository
(继承自 BaseRepository
)与 IdentityUser
一起使用。但是 BaseRepository
有一个约束 where T : BaseEntity
。
BaseEntity
只是我的每个实体继承的类:
public class BaseEntity
{
public int Id { get; set; }
}
问题是
IdentityUser
没有继承它,这就是我这样做的原因:
public class UserRepository : BaseRepository<IdentityUser>
{
}
如何让我的
BaseRepository
使用IdentityUser
?
我遇到了同样的问题,并通过添加
BaseEntity
的抽象来解决它。
我从一个界面开始
IEntity
。就我而言, Id
的类型为 int
,但也可能是 string
或 GUID
。
public interface IEntity
{
public int Id { get; set; }
}
我的基实体类
Entity
实现了IEntity
接口。
public abstract class Entity : IEntity
{
public int Id { get; set; }
}
ApplicationUser
类,它继承于IdentityUser
类并实现了IEntity
接口(我设置的IdentityUser<TKey>.Id
属性的类型与接口中的属性相同,就我而言,TKey
是int
)。您还可以在此类中添加其他属性(如姓名、生日等)。
public class ApplicationUser : IdentityUser<int>, IEntity
{
}
我的其余实体只是继承自
Entity
类。
在我的通用存储库界面
IRepository
中,我将约束where T : Entity
更改为以下内容:
public interface IRepository<T> where T : class, IEntity
{
}
然后通用存储库类
Repository
实现相同的约束。
public abstract class Repository<T> : IRepository<T> where T : class, IEntity
{
}
class
约束很重要(并且它必须按顺序首先出现),因为存储库中使用的DbSet<T>
需要引用类型(public class DbSet<TEntity> : where TEntity : class
)。
现在我的
IUserRepository
界面可以使用ApplicationUser
类了:
public interface IUserRepository : IRepository<ApplicationUser>
{
}
我的
UserRepository
类也可以实现通用存储库:
public class UserRepository : Repository<ApplicationUser>, IUserRepository
{
}
为了简洁起见,我截断了存储库的主体。