加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – 为什么这违反了类型参数’TUser’的约束?

发布时间:2020-12-16 03:35:32 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试使用以下方法自定义asp.net标识实体: public class User : IdentityUserstring,UserClaim,UserRole,UserLoginpublic class UserClaim : IdentityUserClaimstringpublic class UserLogin : IdentityUserLoginstringpublic class UserRole : Identi
我正在尝试使用以下方法自定义asp.net标识实体:

public class User : IdentityUser<string,UserClaim,UserRole,UserLogin>
public class UserClaim : IdentityUserClaim<string>
public class UserLogin : IdentityUserLogin<string>
public class UserRole : IdentityUserRole<string>
public class UserToken : IdentityUserToken<string>
public class Role : IdentityRole<string,RoleClaim>
public class RoleClaim : IdentityRoleClaim<string>

然后我创建了一个DbContext类,如下所示

public class AppDbContext : IdentityDbContext<User,Role,string,UserLogin,RoleClaim,UserToken>

然后配置这些

services
    .AddIdentity<User,Role>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

但我也尝试过

.AddEntityFrameworkStores<AppDbContext,string>()

我在互联网上阅读了很多博客文章,例如this,但是大多数博客都要针对密钥的数据类型进行更改,比如int或Guid.在我的情况下,我不是从字符串更改默认键数据类型.

我在所有这些情况下编译都没问题,但它在运行时抛出错误

System.TypeLoadException
GenericArguments[0],’MyIdentity.Entities.User’,on
‘Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`8[TUser,TRole,TContext,TKey,TUserClaim,TUserRole,TUserLogin,TUserToken]’
violates the constraint of type parameter ‘TUser’.

at System.RuntimeTypeHandle.Instantiate(RuntimeTypeHandle handle,
IntPtr* pInst,int numGenericArgs,ObjectHandleOnStack type) at
System.RuntimeTypeHandle.Instantiate(Type[] inst) at
System.RuntimeType.MakeGenericType(Type[] instantiation)

如果我添加一个自定义的UserStore类,如this post中所述

public class UserStore : UserStore<User,AppDbContext,UserToken>

出现编译错误

CS0311 The type ‘MyIdentity.Entities.Role’ cannot be used as type
parameter ‘TRole’ in the generic type or method ‘UserStore’. There is no implicit reference conversion from
‘MyIdentity.Entities.Role’ to
‘Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole>’

我做错了什么?

解决方法

> According to MSDN,UserStore的约束< TUser>是TUser:IdentityUser.
> Also according to MSDN,IdentityUser:IdentityUser< string,IdentityUserLogin,IdentityUserRole,IdentityUserClaim>.
>根据您的声明,用户:IdentityUser< string,UserLogin>.

长名称很容易错过,所以让我们将IdentityUser别名为D和IdentityUser< string,IdentityUserClaim>作为B.现在上面的内容可以重申为:

> TUser:D(TUser必须是一种D)> D:B(D是一种B)>用户:B(您的用户通常是一种B,但根据需要不是特定的D)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读