From 8e72af7f8cc87384de4bcd48ac5a21b55859071a Mon Sep 17 00:00:00 2001 From: 28810 <28810@YEXIANGQIN> Date: Mon, 20 Apr 2020 08:10:54 +0800 Subject: [PATCH] update --- 自定义特性.md | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/自定义特性.md b/自定义特性.md index 9c0c7cd..dbfa1ac 100644 --- a/自定义特性.md +++ b/自定义特性.md @@ -1,25 +1,43 @@ -抛砖引玉,以下的示例代码,FreeSql 使用 EFCore 的实体特性: +本功能可实现与其他 ORM 使用一套 Attribute,避免维护两份实体特性的烦恼: + +> v1.4.0+ 已自动识别 EFCore 实体特性 Key/Required/NotMapped/Table/Column ```csharp -fsql.CodeFirst.ConfigEntity(a => a.Property(b => b.pkid).IsPrimary(true)); - fsql.Aop.ConfigEntity += (s, e) => { - var attr = e.EntityType.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute), false).FirstOrDefault() as System.ComponentModel.DataAnnotations.Schema.TableAttribute; + var attr = e.EntityType.GetCustomAttributes(typeof(MyTableAttribute), false).FirstOrDefault() as MyTableAttribute; if (attr != null) e.ModifyResult.Name = attr.Name; //表名 //e.ModifyIndexResult.Add(new IndexAttribute("idx_xx", "Title")); //索引 }; fsql.Aop.ConfigEntityProperty += (s, e) => { - if (e.Property.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.KeyAttribute), false).Any()) - e.ModifyResult.IsPrimary = true; //主键 + var attr = e.Property.GetCustomAttributes(typeof(MyColumnAttribute), false).FirstOrDefault() as MyColumnAttribute; + if (attr != null) + e.ModifyResult.Name = attr.Name; //字段名 }; -[System.ComponentModel.DataAnnotations.Schema.Table("xxx")] -class ModelAopConfigEntity { - [System.ComponentModel.DataAnnotations.Key] - [Column(IsPrimary = false)] +[MyTable("xxx")] +class YourEntity +{ + [MyColumn("id")] public int pkid { get; set; } } + +class MyTableAttribute : Attribute +{ + public string Name { get; } + public MyTableAttribute(string name) + { + this.Name = name; + } +} +class MyColumnAttribute : Attribute +{ + public string Name { get; } + public MyColumnAttribute(string name) + { + this.Name = name; + } +} ``` ## 优先级