Ef Core花里胡哨系列(6) XML注释同步到数据库注释

Ef Core花里胡哨系列(6) XML注释同步到数据库注释

参考文档:C#读取注释的方法

准备读取Xml的工具类

可以根据[参考文档]获取一个简单读取注释的方法。

实现DbContext

我们通过重写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; }
}
posted @ 2024-01-02 17:19  胖纸不争  阅读(239)  评论(0编辑  收藏  举报