带有 IdentityUser 的通用存储库

问题描述 投票:0回答:1

我最近开始使用 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

asp.net-mvc oauth asp.net-mvc-5 oauth-2.0 asp.net-identity
1个回答
0
投票

我遇到了同样的问题,并通过添加

BaseEntity
的抽象来解决它。

I实体

我从一个界面开始

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
{
}

为了简洁起见,我截断了存储库的主体。

© www.soinside.com 2019 - 2024. All rights reserved.