参考文档:C#读取注释的方法
可以根据[参考文档]获取一个简单读取注释的方法。
我们通过重写OnModelCreating
方法,在生成数据库表时,使用FluentApi
指定对应表以及其属性的Comment
即可将Xml注释转为数据库的Comment
。
public class SampleDbContext : DbContext
{
public SampleDbContext(DbContextOptions<SampleDbContext> options) : base(options) { }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var xmlCommentHelper = new XmlCommentHelper();
xmlCommentHelper.LoadAll();
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var typeComment = xmlCommentHelper.GetTypeComment(entityType.ClrType);
modelBuilder.Entity(entityType.ClrType).ToTable(t => t.HasComment(typeComment));
foreach (var property in entityType.ClrType.GetProperties().Where(x => x.IsPubliclyWritable()))
{
var propertyComment = xmlCommentHelper.GetFieldOrPropertyComment(property);
modelBuilder.Entity(entityType.ClrType).Property(property.Name).HasComment(propertyComment);
}
}
base.OnModelCreating(modelBuilder);
}
}
/// <summary>
/// 用户表
/// </summary>
public class User
{
/// <summary>
/// Id
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public required string Name { get; set; }
/// <summary>
/// 邮箱
/// </summary>
public required string Email { get; set; }
}