欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.Net Core Identity 骚断腿的究极魔改实体类

程序员文章站 2022-03-03 09:29:41
前言 默认的 Identity 实体类型在大多数时候已经基本够用,很多时候也只是稍微在 IdentityUser 类中增加一些自定义数据字段,比如头像。这次,我要向园友隆重介绍我魔改之后的 Identity 实体类,能支持一些特别风骚的操作。当然也完全兼容内置的 UserManager、RoleMa ......

前言

       默认的 identity 实体类型在大多数时候已经基本够用,很多时候也只是稍微在 identityuser 类中增加一些自定义数据字段,比如头像。这次,我要向园友隆重介绍我魔改之后的 identity 实体类,能支持一些特别风骚的操作。当然也完全兼容内置的 usermanager、rolemanager 和 signinmanager,毕竟也是从内置类型继承扩展出来的。

正文

       魔改的实体类基于一组我自定义实体接口,这组接口我也实现了一组打包好的基础类型。因为 identity 系列实体类型已经存在,而 c# 不支持多重继承,所以只能把这些代码在魔改的 identity 实体类中粘贴几次了。

       先来看看这些基本接口吧:

  1     /// <summary>
  2     /// 软删除接口
  3     /// </summary>
  4     public interface ilogicallydeletable
  5     {
  6         /// <summary>
  7         /// 逻辑删除标记
  8         /// </summary>
  9         bool isdeleted { get; set; }
 10     }
 11 
 12     /// <summary>
 13     /// 活动状态标记接口
 14     /// </summary>
 15     public interface iactivecontrollable
 16     {
 17         /// <summary>
 18         /// 活动状态标记
 19         /// </summary>
 20         bool? active { get; set; }
 21     }
 22 
 23     /// <summary>
 24     /// 乐观并发接口
 25     /// </summary>
 26     public interface ioptimisticconcurrencysupported
 27     {
 28         /// <summary>
 29         /// 行版本,乐观并发锁
 30         /// </summary>
 31         [concurrencycheck]
 32         string concurrencystamp { get; set; }
 33     }
 34 
 35     /// <summary>
 36     /// 插入顺序记录接口
 37     /// </summary>
 38     public interface istorageorderrecordable
 39     {
 40         /// <summary>
 41         /// 非自增顺序字段作为主键类型
 42         /// 应该在此列建立聚集索引避免随机的字段值导致数据库索引性能下降
 43         /// 同时保存数据插入先后的信息
 44         /// </summary>
 45         long insertorder { get; set; }
 46     }
 47 
 48     /// <summary>
 49     /// 创建时间记录接口
 50     /// </summary>
 51     public interface icreationtimerecordable
 52     {
 53         /// <summary>
 54         /// 实体创建时间
 55         /// </summary>
 56         datetimeoffset creationtime { get; set; }
 57     }
 58 
 59     /// <summary>
 60     /// 最后修改时间记录接口
 61     /// </summary>
 62     public interface ilastmodificationtimerecordable
 63     {
 64         /// <summary>
 65         /// 最后一次修改时间
 66         /// </summary>
 67         datetimeoffset lastmodificationtime { get; set; }
 68     }
 69 
 70     /// <summary>
 71     /// 创建人id记录接口
 72     /// </summary>
 73     /// <typeparam name="tidentitykey">创建人主键类型</typeparam>
 74     public interface icreatorrecordable<tidentitykey>
 75         where tidentitykey : struct, iequatable<tidentitykey>
 76     {
 77         /// <summary>
 78         /// 创建人id
 79         /// </summary>
 80         tidentitykey? creatorid { get; set; }
 81     }
 82 
 83     /// <summary>
 84     /// 创建人记录接口
 85     /// </summary>
 86     /// <typeparam name="tidentitykey">创建人主键类型</typeparam>
 87     /// <typeparam name="tidentityuser">创建人类型</typeparam>
 88     public interface icreatorrecordable<tidentitykey, tidentityuser> : icreatorrecordable<tidentitykey>
 89         where tidentitykey : struct , iequatable<tidentitykey>
 90         where tidentityuser : ientity<tidentitykey>
 91     {
 92         /// <summary>
 93         /// 创建人
 94         /// </summary>
 95         tidentityuser creator { get; set; }
 96     }
 97 
 98     /// <summary>
 99     /// 上次修改人id记录接口
100     /// </summary>
101     /// <typeparam name="tidentitykey">上次修改人主键类型</typeparam>
102     public interface ilastmodifierrecordable<tidentitykey>
103         where tidentitykey : struct, iequatable<tidentitykey>
104     {
105         /// <summary>
106         /// 上一次修改人id
107         /// </summary>
108         tidentitykey? lastmodifierid { get; set; }
109     }
110 
111     /// <summary>
112     /// 上次修改人记录接口
113     /// </summary>
114     /// <typeparam name="tidentitykey">上次修改人主键类型</typeparam>
115     /// <typeparam name="tidentityuser">上次修改人类型</typeparam>
116     public interface ilastmodifierrecordable<tidentitykey, tidentityuser> : ilastmodifierrecordable<tidentitykey>
117         where tidentitykey : struct, iequatable<tidentitykey>
118         where tidentityuser : ientity<tidentitykey>
119     {
120         /// <summary>
121         /// 上一次修改人
122         /// </summary>
123         tidentityuser lastmodifier { get; set; }
124     }

       这些基本接口每一个都对应了一个基本功能。还有一个稍微复杂的树形数据结构接口:

 1     /// <summary>
 2     /// 树形数据接口
 3     /// </summary>
 4     /// <typeparam name="t">节点数据类型</typeparam>
 5     public interface itree<t>
 6     {
 7         /// <summary>
 8         /// 父节点
 9         /// </summary>
10         t parent { get; set; }
11 
12         /// <summary>
13         /// 子节点集合
14         /// </summary>
15         ilist<t> children { get; set; }
16 
17         /// <summary>
18         /// 节点深度,根的深度为0
19         /// </summary>
20         int depth { get; }
21 
22         /// <summary>
23         /// 是否是根节点
24         /// </summary>
25         bool isroot { get; }
26 
27         /// <summary>
28         /// 是否是叶节点
29         /// </summary>
30         bool isleaf { get; }
31 
32         /// <summary>
33         /// 是否有子节点
34         /// </summary>
35         bool haschildren { get; }
36 
37         /// <summary>
38         /// 节点路径(unix路径格式,以“/”分隔)
39         /// </summary>
40         string path { get; }
41     }

       然后是打包接口,主要是把基本接口打包到一个统一接口,方便批量使用:

 1     /// <summary>
 2     /// 实体接口
 3     /// </summary>
 4     public interface ientity {}
 5 
 6     /// <summary>
 7     /// 泛型实体接口,约束id属性
 8     /// </summary>
 9     public interface ientity<tkey> : ientity
10         where tkey : iequatable<tkey>
11     {
12         tkey id { get; set; }
13     }
14 
15     /// <summary>
16     /// 领域实体接口,主要是整合各个小接口
17     /// </summary>
18     public interface idomainentity : ientity
19         , ilogicallydeletable
20         , icreationtimerecordable
21         , ilastmodificationtimerecordable
22         , inotifypropertychanged
23         , inotifypropertychangedextension
24         , ipropertychangetrackable
25     {}
26 
27     /// <summary>
28     /// 泛型领域实体接口
29     /// </summary>
30     public interface idomainentity<tkey> : ientity<tkey>
31         , idomainentity
32         where tkey : struct, iequatable<tkey>
33     {}

       树形数据结构也有一套:

 1     /// <summary>
 2     /// 树形实体接口
 3     /// </summary>
 4     /// <typeparam name="t">实体类型</typeparam>
 5     public interface itreeentity<t> : ientity, itree<t>
 6     {
 7     }
 8 
 9     /// <summary>
10     /// 树形实体接口
11     /// </summary>
12     /// <typeparam name="tkey">主键类型</typeparam>
13     /// <typeparam name="tentity">实体类型</typeparam>
14     public interface itreeentity<tkey, tentity> : itreeentity<tentity>, ientity<tkey>
15     where tkey : iequatable<tkey>
16     where tentity : itreeentity<tkey, tentity>
17     {
18     }
19 
20     /// <summary>
21     /// 树形领域实体接口
22     /// </summary>
23     /// <typeparam name="t">数据类型</typeparam>
24     public interface idomaintreeentity<t> :
25         idomainentity
26         , itreeentity<t>
27     {
28     }
29 
30     /// <summary>
31     /// 树形领域实体接口
32     /// </summary>
33     /// <typeparam name="tkey">主键类型</typeparam>
34     /// <typeparam name="tentity">树形实体类型</typeparam>
35     public interface idomaintreeentity<tkey, tentity> :
36         idomaintreeentity<tentity>
37         , idomainentity<tkey>
38         , itreeentity<tkey, tentity>
39 
40         where tkey : struct, iequatable<tkey>
41         where tentity : idomaintreeentity<tkey, tentity>
42     {
43         tkey? parentid { get; set; }
44     }

       最后还有几个特别用处的接口:

 1     /// <summary>
 2     /// 跟踪属性的变更
 3     /// </summary>
 4     public interface ipropertychangetrackable
 5     {
 6         /// <summary>
 7         /// 判断指定的属性或任意属性是否被变更过
 8         /// </summary>
 9         /// <param name="names">指定要判断的属性名数组,如果为空(null)或空数组则表示判断任意属性</param>
10         /// <returns>
11         ///    <para>如果指定的<paramref name="names"/>参数有值,当只有参数中指定的属性发生过更改则返回真(true),否则返回假(false)</para>
12         ///    <para>如果指定的<paramref name="names"/>参数为空(null)或空数组,当实体中任意属性发生过更改则返回真(true),否则返回假(false)</para>
13         ///    </returns>
14         bool haschanges(params string[] names);
15 
16         /// <summary>
17         /// 获取实体中发生过变更的属性集
18         /// </summary>
19         /// <returns>如果实体没有属性发生过变更,则返回空白字典,否则返回被变更过的属性键值对</returns>
20         idictionary<string, object> getchanges();
21 
22         /// <summary>
23         /// 重置指定的属性或任意属性变更状态(为未变更)
24         /// </summary>
25         /// <param name="names">指定要重置的属性名数组,如果为空(null)或空数组则表示重置所有属性的变更状态(为未变更)</param>
26         void resetpropertychangestatus(params string[] names);
27     }
28 
29     /// <summary>
30     /// 多对多导航实体接口
31     /// </summary>
32     /// <typeparam name="tidentitykey">身份实体主键类型</typeparam>
33     /// <typeparam name="tidentityuser">身份实体类型</typeparam>
34     public interface imanytomanyreferenceentity<tidentitykey, tidentityuser> : imanytomanyreferenceentity<tidentitykey>
35         , icreatorrecordable<tidentitykey, tidentityuser>
36         where tidentitykey : struct, iequatable<tidentitykey>
37         where tidentityuser : ientity<tidentitykey>
38     {
39     }
40 
41     /// <summary>
42     /// 多对多导航实体接口
43     /// </summary>
44     /// <typeparam name="tidentitykey">身份实体主键类型</typeparam>
45     public interface imanytomanyreferenceentity<tidentitykey> : imanytomanyreferenceentity
46         , icreatorrecordable<tidentitykey>
47         where tidentitykey : struct, iequatable<tidentitykey>
48     {
49     }
50 
51     /// <summary>
52     /// 多对多导航实体接口
53     /// </summary>
54     public interface imanytomanyreferenceentity : ientity
55         , icreationtimerecordable
56     {
57     }

       至此,基本上用到的接口就定义好了,接下来就是魔改 identity 实体类,这里以 identityrole 为例,其他的可以到我的项目中查看,大同小异:

  1     public class applicationrole : applicationrole<int, applicationuser, applicationrole, applicationuserrole, applicationroleclaim>
  2         , istorageorderrecordable
  3     {
  4         public applicationrole() { }
  5         public applicationrole(string rolename) => name = rolename;
  6 
  7         public virtual long insertorder { get; set; }
  8     }
  9 
 10     public abstract class applicationrole<tkey, tidentityuser, tidentityrole, tuserrole, troleclaim> : identityrole<tkey>
 11         , idomaintreeentity<tkey, tidentityrole>
 12         , ioptimisticconcurrencysupported
 13         , icreatorrecordable<tkey, tidentityuser>
 14         , ilastmodifierrecordable<tkey, tidentityuser>
 15         where tkey : struct, iequatable<tkey>
 16         where tidentityuser : ientity<tkey>
 17         where tuserrole : applicationuserrole<tkey, tidentityuser, tidentityrole>
 18         where troleclaim : applicationroleclaim<tkey, tidentityuser, tidentityrole>
 19         where tidentityrole : applicationrole<tkey, tidentityuser, tidentityrole, tuserrole, troleclaim>
 20     {
 21         #region 重写基类属性使属性变更通知事件生效
 22 
 23         public override tkey id { get => base.id; set => base.id = value; }
 24         public override string concurrencystamp { get => base.concurrencystamp; set => base.concurrencystamp = value; }
 25         public override string name { get => base.name; set => base.name = value; }
 26         public override string normalizedname { get => base.normalizedname; set => base.normalizedname = value; }
 27 
 28         #endregion
 29 
 30         public string description { get; set; }
 31 
 32         /// <summary>
 33         /// 需要使用.include(r => r.userroles).theninclude(ur => ur.role)预加载或启用延迟加载
 34         /// </summary>
 35         [notmapped]
 36         public virtual ienumerable<tidentityuser> users => userroles?.select(ur => ur.user);
 37 
 38         #region 导航属性
 39 
 40         public virtual list<tuserrole> userroles { get; set; } = new list<tuserrole>();
 41 
 42         public virtual list<troleclaim> roleclaims { get; set; } = new list<troleclaim>();
 43 
 44         #endregion
 45 
 46         #region idomaintreeentity成员
 47 
 48         public virtual tkey? parentid { get; set; }
 49 
 50         #endregion
 51 
 52         #region ientity成员
 53 
 54         public virtual bool? active { get; set; } = true;
 55         public virtual bool isdeleted { get; set; }
 56         public virtual datetimeoffset creationtime { get; set; } = datetimeoffset.now;
 57         public virtual datetimeoffset lastmodificationtime { get; set; } = datetimeoffset.now;
 58 
 59         #endregion
 60 
 61         #region idomainentity成员
 62 
 63         public virtual tkey? creatorid { get; set; }
 64         public virtual tidentityuser creator { get; set; }
 65         public virtual tkey? lastmodifierid { get; set; }
 66         public virtual tidentityuser lastmodifier { get; set; }
 67 
 68         #endregion
 69 
 70         #region itree成员
 71 
 72         public virtual tidentityrole parent { get; set; }
 73 
 74         public virtual ilist<tidentityrole> children { get; set; }
 75 
 76         [donotnotify, notmapped]
 77         public virtual int depth => parent?.depth + 1 ?? 0;
 78 
 79         [donotnotify, notmapped]
 80         public virtual bool isroot => parent == null;
 81 
 82         [donotnotify, notmapped]
 83         public virtual bool isleaf => children?.count == 0;
 84 
 85         [donotnotify, notmapped]
 86         public virtual bool haschildren => !isleaf;
 87 
 88         [donotnotify, notmapped]
 89         public virtual string path => parent == null ? id.tostring() : $@"{parent.path}/{id}";
 90 
 91         #endregion
 92 
 93         #region ipropertychangetrackable成员
 94 
 95         private static readonly object locker = new object();
 96         private static readonly dictionary<type, string[]> propertynamesdictionary = new dictionary<type, string[]>();
 97 
 98         private readonly bitarray _propertychangemask;
 99 
100         /// <summary>
101         /// 全局属性变更通知事件处理器
102         /// </summary>
103         public static propertychangedeventhandler publicpropertychangedeventhandler { get; set; }
104 
105         /// <summary>
106         /// 初始化用于跟踪属性变更所需的属性信息
107         /// </summary>
108         protected applicationrole()
109         {
110             //判断类型是否已经加入字典
111             //将未加入的类型添加进去(一般为该类对象首次初始化时)
112             var type = this.gettype();
113             if (!propertynamesdictionary.containskey(type))
114             {
115                 lock (locker)
116                 {
117                     if (!propertynamesdictionary.containskey(type))
118                     {
119                         propertynamesdictionary.add(type, type.getproperties()
120                             .orderby(property => property.name)
121                             .select(property => property.name).toarray());
122                     }
123                 }
124             }
125 
126             //初始化属性变更掩码
127             _propertychangemask = new bitarray(propertynamesdictionary[type].length, false);
128 
129             //注册全局属性变更事件处理器
130             if (publicpropertychangedeventhandler != null)
131             {
132                 propertychanged += publicpropertychangedeventhandler;
133             }
134         }
135 
136         /// <summary>
137         /// 属性变更事件
138         /// </summary>
139         public event propertychangedeventhandler propertychanged;
140         public event propertychangedextensioneventhandler propertychangedextension;
141 
142         /// <summary>
143         /// 内部属性变更事件处理器
144         /// </summary>
145         /// <param name="propertyname">属性名</param>
146         /// <param name="oldvalue">旧值</param>
147         /// <param name="newvalue">新值</param>
148         protected virtual void onpropertychanged(string propertyname, object oldvalue, object newvalue)
149         {
150             //perform property validation
151 
152             _propertychangemask[array.indexof(propertynamesdictionary[this.gettype()], propertyname)] = true;
153 
154             propertychanged?.invoke(this, new propertychangedeventargs(propertyname));
155             propertychangedextension?.invoke(this, new propertychangedextensioneventargs(propertyname, oldvalue, newvalue));
156         }
157 
158         /// <summary>
159         /// 判断指定的属性或任意属性是否被变更过(<see cref="ipropertychangetrackable"/>接口的实现)
160         /// </summary>
161         /// <param name="names">指定要判断的属性名数组,如果为空(null)或空数组则表示判断任意属性。</param>
162         /// <returns>
163         ///    <para>如果指定的<paramref name="names"/>参数有值,当只有参数中指定的属性发生过更改则返回真(true),否则返回假(false);</para>
164         ///    <para>如果指定的<paramref name="names"/>参数为空(null)或空数组,当实体中任意属性发生过更改则返回真(true),否则返回假(false)。</para>
165         ///    </returns>
166         public bool haschanges(params string[] names)
167         {
168             if (!(names?.length > 0))
169             {
170                 foreach (bool mask in _propertychangemask)
171                 {
172                     if (mask == true)
173                     {
174                         return true;
175                     }
176                 }
177 
178                 return false;
179             }
180 
181             var type = this.gettype();
182             foreach (var name in names)
183             {
184                 var index = array.indexof(propertynamesdictionary[type], name);
185                 if (index >= 0 && _propertychangemask[index] == true)
186                 {
187                     return true;
188                 }
189             }
190 
191             return false;
192         }
193 
194         /// <summary>
195         /// 获取实体中发生过变更的属性集(<see cref="ipropertychangetrackable"/>接口的实现)
196         /// </summary>
197         /// <returns>如果实体没有属性发生过变更,则返回空白字典,否则返回被变更过的属性键值对</returns>
198         public idictionary<string, object> getchanges()
199         {
200             dictionary<string, object> changedictionary = new dictionary<string, object>();
201             var type = this.gettype();
202             for (int i = 0; i < _propertychangemask.length; i++)
203             {
204                 if (_propertychangemask[i] == true)
205                 {
206                     changedictionary.add(propertynamesdictionary[type][i],
207                         type.getproperty(propertynamesdictionary[type][i])?.getvalue(this));
208                 }
209             }
210 
211             return changedictionary;
212         }
213 
214         /// <summary>
215         /// 重置指定的属性或任意属性变更状态(为未变更)(<see cref="ipropertychangetrackable"/>接口的实现)
216         /// </summary>
217         /// <param name="names">指定要重置的属性名数组,如果为空(null)或空数组则表示重置所有属性的变更状态(为未变更)</param>
218         public void resetpropertychangestatus(params string[] names)
219         {
220             if (names?.length > 0)
221             {
222                 var type = this.gettype();
223                 foreach (var name in names)
224                 {
225                     var index = array.indexof(propertynamesdictionary[type], name);
226                     if (index >= 0)
227                     {
228                         _propertychangemask[index] = false;
229                     }
230                 }
231             }
232             else
233             {
234                 _propertychangemask.setall(false);
235             }
236         }
237 
238         #endregion
239     }

       可以看到我在为 identityrole 添加接口实现的时候添加的是 idomaintreeentity 接口。在这里我把 role 改成了树形数据类型,也就是说一个角色可以是另一个角色的子角色,构成树状关系。当然如果就当作普通的 role 来使用也没有任何问题,这个扩展完全不会破坏任何内置功能,没有任何侵入性,按需选用就好,至于能发挥什么作用,完全看脑洞有多大 (●'◡'●)

       然而,这还不是全部,不然就对不起魔改的名号了。现在看见的代码还不是最终形态。因为使用了 propertychanged.fody 这个库,所有的实体都可以向外发送属性变更通知,至于能发挥什么作用,还是看脑洞。

       代码最终形态预览(此处使用了 ilspy 反编译引擎的 nuget 包,详情见我之前的博客c# 编译器 和 反编译器,你要哪个(歪头)? 我全都要(捏拳)!):

Asp.Net Core Identity 骚断腿的究极魔改实体类

       魔改部分还不止这些,但是和我接下来打算介绍的部分存在重叠,所以剩下的部分就和接下来的介绍放在一起了,会新开一篇博客。

       各位观众老爷对我的魔改实体类有什么感想欢迎评论交流。可以到下方我的 github 存储库下载项目运行体验效果。

 

       转载请完整保留以下内容并在显眼位置标注,未经授权删除以下内容进行转载盗用的,保留追究法律责任的权利!

  本文地址:https://www.cnblogs.com/coredx/p/12310010.html

  完整源代码:github

  里面有各种小东西,这只是其中之一,不嫌弃的话可以star一下。