【繁星Code】如何在EF将实体注释写入数据库中
最近在项目中需要把各个字段的释义写到数据库中,该项目已经上线很长时间了,数据库中的字段没有上千也有上百个,要是一个项目一个项目打开然后再去找对应字段查看什么意思,估计要到明年过年了。由于项目中使用EntityFramework,本身这个项目只有手动设置字段注释的功能,Coder平时写代码的时候都懒得写注释,更别提能在配置数据库的时候将注释配置进去,所以如何在EF中自动将实体注释写入数据库,减轻Coder的压力(ru he tou lan)尤为重要。gitee地址: https://gitee.com/lbqman/Blog20210206.git
。下面进入正题。
一、实现思路
在FluentAPI中提供了HasComment方法,如下
///Configures a comment to be applied to the column
/// The type of the property being configured.
/// The builder for the property being configured.
/// The comment for the column.
/// The same builder instance so that multiple calls can be chained.
public static PropertyBuilder HasComment(
[NotNull] this PropertyBuilder propertyBuilder,
[CanBeNull] string comment)
{
return (PropertyBuilder) propertyBuilder.HasComment(comment);
}
也就是说我们要获取到实体对象的注释xml,然后读取对应的字段注释,自动调用改方法即可。需要解决的问题大概有以下几点。
- 如何获取当前配置的字段;
- 加载Xml,并根据字段获取对应的注释;
- 如何将枚举的各项信息都放入注释中;
二、实现方法
1.如何获取当前配置的字段
在获取xml的注释中,需要的信息有实体对应的类型以及对应的字段。而包含这两种类型的方法只有Property这个方法,该方法的出入参如下:
public virtual PropertyBuilder Property(
[NotNull] Expression<Func> propertyExpression);
所以我们准备对这个方法进行改造。并且根据传入的propertyExpression获取字段名称。方法如下:
public static PropertyBuilder SummaryProperty(
this EntityTypeBuilder entityTypeBuilder,
Expression<Func> propertyExpression)
where TEntity : class
根据表达式获取字段名称如下:
public static MemberInfo GetMember(this Expression<Func> expression)
{
MemberExpression memberExp;
if (expression.Body is UnaryExpression unaryExpression)
memberExp = unaryExpression.Operand as MemberExpression;
else
memberExp = expression.Body as MemberExpression;
8
return memberExp?.Member;
}
2.加载Xml,并根据字段获取对应的注释
VS中的Xml格式不在此处过多解释,属性、方法等注释可以根据规律去获取。此处需要注意的是当字段是从父类继承而来并且父类属于不同的dll时,需要获取父类所在dll的xml注释才行,另外枚举也需要同样去处理。虽然获取Xml数据的方法只在更新数据库时才调用,但是还是需要使用字典将数据缓存下来,方便下次快速获取。具体代码如下:
///
/// xml注释获取器
///
internal static class SummaryXmlCacheProvider
{
#region TClass
7
///
/// 根据类型初始化该类所在程序集的xml
///
///
internal static void InitSummaryXml()
{
var assembly = Assembly.GetAssembly(typeof(TClass));
SerializeXmlFromAssembly(assembly);
}
17
///
/// 根据类型获取该类所在程序集的xml
///
///
///
internal static Dictionary GetSummaryXml()
{
var assembly = Assembly.GetAssembly(typeof(TClass));
return SummaryCache[assembly];
}
28
///
/// 获取该类在xml的key
///
///
///
internal static string GetClassTypeKey()
{
return TableSummaryRuleProvider.TypeSummaryKey(typeof(TClass).FullName);
}
38
#endregion
40
#region TProperty
42
///
/// 根据类型以及字段初始化该类所在程序集的xml
///
///
///
///
internal static void InitSummaryXml(Expression<Func> propertyExpression)
{
var propertyAssembly = GetPropertyAssembly(propertyExpression);
SerializeXmlFromAssembly(propertyAssembly);
}
54
///
/// 根据类型以及字段获取该类所在程序集的xml
///
///
///
///
///
internal static Dictionary GetSummaryXml(
Expression<Func> propertyExpression)
{
var propertyAssembly = GetPropertyAssembly(propertyExpression);
return SummaryCache[propertyAssembly];
}
68
///
/// 获取该类以及字段所在xml的key
///
///
///
///
///
internal static string GetPropertyTypeKey(
Expression<Func> propertyExpression)
{
var memberName = propertyExpression.GetMember().Name;
var propertyInfo = GetPropertyInfo(propertyExpression);
var propertyKey =
$"{propertyInfo.DeclaringType.Namespace}.{propertyInfo.DeclaringType.Name}.{memberName}";
return PropertySummaryRuleProvider.PropertyTypeSummaryKey(propertyKey);
}
85
#endregion
87
#region TEnum
89
///
/// 获取枚举字段的描述信息
///
///
///
///
///
internal static string GetEnumPropertyDescription(Expression<Func> propertyExpression)
{
var propertyInfo = GetPropertyInfo(propertyExpression);
if (!propertyInfo.PropertyType.IsEnum)
return string.Empty;
var enumType = propertyInfo.PropertyType;
SerializeXmlFromAssembly(enumType.Assembly);
var propertySummaryDic = SummaryCache[enumType.Assembly];
var enumNames = enumType.GetEnumNames();
var enumDescDic = enumType.GetNameAndValues();
var enumSummaries = new List();
foreach (var enumName in enumNames)
{
var propertyEnumKey = PropertySummaryRuleProvider.EnumTypeSummaryKey($"{enumType.FullName}.{enumName}");
var enumSummary = propertySummaryDic.ContainsKey(propertyEnumKey)
? propertySummaryDic[propertyEnumKey]
: string.Empty;
var enumValue = enumDescDic[enumName];
enumSummaries.Add(PropertySummaryRuleProvider.EnumTypeSummaryFormat(enumValue,enumName,enumSummary));
}
117
return string.Join(";", enumSummaries);
119
}
121
#endregion
123
///
/// 根据表达式获取属性所在的程序集
///
///
///
///
///
private static Assembly GetPropertyAssembly(
Expression<Func> propertyExpression)
{
var propertyInfo = GetPropertyInfo(propertyExpression);
var propertyAssembly = propertyInfo.Module.Assembly;
return propertyAssembly;
}
138
///
/// 根据表达式获取字段属性
///
///
///
///
///
private static PropertyInfo GetPropertyInfo(
Expression<Func> propertyExpression)
{
var entityType = typeof(TClass);
var memberName = propertyExpression.GetMember().Name;
var propertyInfo = entityType.GetProperty(memberName, typeof(TProperty));
if (propertyInfo == null || propertyInfo.DeclaringType == null)
throw new ArgumentNullException($"this property {memberName} is not belong to {entityType.Name}");
154
return propertyInfo;
}
157
///
/// 根据程序集初始化xml
///
///
private static void SerializeXmlFromAssembly(Assembly assembly)
{
var assemblyPath = assembly.Location;
var lastIndexOf = assemblyPath.LastIndexOf(".dll", StringComparison.Ordinal);
var xmlPath = assemblyPath.Remove(lastIndexOf, 4) + ".xml";
167
if (SummaryCache.ContainsKey(assembly))
return;
var xmlDic = new Dictionary();
if (!File.Exists(xmlPath))
{
Console.WriteLine($"未能加载xml文件,原因:xml文件不存在,path:{xmlPath}");
SummaryCache.Add(assembly, xmlDic);
return;
}
177
var doc = new XmlDocument();
doc.Load(xmlPath);
var members = doc.SelectNodes("doc/members/member");
if (members == null)
{
Console.WriteLine($"未能加载xml文件,原因:doc/members/member节点不存在");
SummaryCache.Add(assembly, xmlDic);
return;
}
187
foreach (XmlElement member in members)
{
var name = member.Attributes["name"].InnerText.Trim();
if (string.IsNullOrWhiteSpace(name))
continue;
xmlDic.Add(name, member.SelectSingleNode("summary")?.InnerText.Trim());
}
195
SummaryCache.Add(assembly, xmlDic);
}
198
///
/// xml注释缓存
///
private static Dictionary<Assembly, Dictionary> SummaryCache { get; } =
new Dictionary<Assembly, Dictionary>();
}
3.如何将枚举的各项信息都放入注释中
上面的两个步骤已经根据表达式将字段的注释获取到,直接调用EF提供的HasComment即可。见代码:
public static PropertyBuilder SummaryProperty(
this EntityTypeBuilder entityTypeBuilder,
Expression<Func> propertyExpression)
where TEntity : class
{
SummaryXmlCacheProvider.InitSummaryXml(propertyExpression);
var entitySummaryDic = SummaryXmlCacheProvider.GetSummaryXml(propertyExpression);
var propertyKey = SummaryXmlCacheProvider.GetPropertyTypeKey(propertyExpression);
var summary = entitySummaryDic.ContainsKey(propertyKey) ? entitySummaryDic[propertyKey] : string.Empty;
var enumDescription = SummaryXmlCacheProvider.GetEnumPropertyDescription(propertyExpression);
summary = string.IsNullOrWhiteSpace(enumDescription) ? summary : $"{summary}:{enumDescription}";
return string.IsNullOrWhiteSpace(summary)
? entityTypeBuilder.Property(propertyExpression)
: entityTypeBuilder.Property(propertyExpression).HasComment(summary);
}
同时也可以设置表的注释以及表的名称。如下:
public static EntityTypeBuilder SummaryToTable(
this EntityTypeBuilder entityTypeBuilder, bool hasTableComment = true,
Func tablePrefix = null)
where TEntity : class
{
var tableName = GetTableName(tablePrefix);
return hasTableComment
? entityTypeBuilder.ToTable(tableName)
.SummaryHasComment()
: entityTypeBuilder.ToTable(tableName);
}
12
public static EntityTypeBuilder SummaryHasComment(
this EntityTypeBuilder entityTypeBuilder) where TEntity : class
{
SummaryXmlCacheProvider.InitSummaryXml();
var entityDic = SummaryXmlCacheProvider.GetSummaryXml();
var tableKey = SummaryXmlCacheProvider.GetClassTypeKey();
var summary = entityDic.ContainsKey(tableKey) ? entityDic[tableKey] : string.Empty;
return string.IsNullOrWhiteSpace(summary) ? entityTypeBuilder : entityTypeBuilder.HasComment(summary);
}
22
private static string GetTableName(Func tablePrefix)
{
return typeof(TEntity).Name.Replace("Entity", $"Tb{tablePrefix?.Invoke()}");
}
搞定。
三、效果展示
运行Add-Migration InitDb即可查看生成的代码。
public partial class InitDb : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "TbGood",
columns: table => new
{
Id = table.Column(nullable: false, comment: "主键")
.Annotation("SqlServer:Identity", "1, 1"),
CreateTime = table.Column(nullable: false, comment: "创建时间"),
CreateName = table.Column(maxLength: 64, nullable: false, comment: "创建人姓名"),
UpdateTime = table.Column(nullable: true, comment: "更新时间"),
UpdateName = table.Column(maxLength: 64, nullable: true, comment: "更新人姓名"),
Name = table.Column(maxLength: 64, nullable: false, comment: "商品名称"),
GoodType = table.Column(nullable: false, comment: "物品类型:(0,Electronic) 电子产品;(1,Clothes) 衣帽服装;(2,Food) 食品;(3,Other) 其他物品"),
Description = table.Column(maxLength: 2048, nullable: true, comment: "物品描述"),
Store = table.Column(nullable: false, comment: "储存量")
},
constraints: table =>
{
table.PrimaryKey("PK_TbGood", x => x.Id);
},
comment: "商品实体类");
25
migrationBuilder.CreateTable(
name: "TbOrder",
columns: table => new
{
Id = table.Column(nullable: false, comment: "主键")
.Annotation("SqlServer:Identity", "1, 1"),
CreateTime = table.Column(nullable: false, comment: "创建时间"),
CreateName = table.Column(maxLength: 64, nullable: false, comment: "创建人姓名"),
UpdateTime = table.Column(nullable: true, comment: "更新时间"),
UpdateName = table.Column(maxLength: 64, nullable: true, comment: "更新人姓名"),
GoodId = table.Column(nullable: false, comment: "商品Id"),
OrderStatus = table.Column(nullable: false, comment: "订单状态:(0,Ordered) 已下单;(1,Payed) 已付款;(2,Complete) 已付款;(3,Cancel) 已取消"),
OrderTime = table.Column(nullable: false, comment: "下订单时间"),
Address = table.Column(maxLength: 2048, nullable: false, comment: "订单地址"),
UserName = table.Column(maxLength: 16, nullable: false, comment: "收件人姓名"),
TotalAmount = table.Column(nullable: false, comment: "总金额")
},
constraints: table =>
{
table.PrimaryKey("PK_TbOrder", x => x.Id);
},
comment: "订单实体类");
}
49
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TbGood");
54
migrationBuilder.DropTable(
name: "TbOrder");
}
}
四、写在最后
此种方法是在我目前能想起来比较方便生成注释的方法了,另外还想过EntityTypeBuilder中的Property方法,最后还是放弃了,因为EntityTypeBuilder是由ModelBuilder生成,而ModelBuilder又是ModelSource中的CreateModel方法产生,最后一路深扒到DbContext中,为了搞这个注释得不偿失,最后才采取了上述的方法。若是大佬有更好的方法,恭请分享。