如何自动生成类字段注释到数据库?首先是实体框架代码

问题描述 投票:0回答:2

我使用的是实体框架代码优先模式,但是如何自动生成类字段注释到数据库?

示例:

[Table("User")]
public class User
{
     /// <summary>
     /// Id
     /// </summary>
     public long Id{get;set;}

     /// <summary>
     /// this is name
     /// </summary>
     public string name{get;set;}
}

SQL 应该是这样的:

CREATE TABLE User 
(
    id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'Id',
    name VARCHAR(128) NOT NULL COMMENT 'this is name'
)

有人知道如何实现这一目标吗?

entity-framework code-first
2个回答
0
投票

除了“不”之外,给出更具体的答案。在评论中。

基本上不可能实现这一点,因为注释不会传递到作为生成迁移元素基础的编译对象。

此外,请考虑免费评论部分可能包含可用作书籍的评论(即评论没有限制,但数据库中有评论)。

您可以考虑使用可能适合您需求的新属性,例如:

[DbComment('This field is containing bla bla')]
public int FooBar {get; set;}

然后可以通过覆盖 Sql-Generation 类将其合并到数据库生成过程中。

使用这种方式的问题仍然是评论需要维护两次。


0
投票

现在,可以使用它:

using Namotion.Reflection; //need Namotion.Reflection in nuget

//Please enable GenerateDocumentationFile in project generation
private static void SetComment(ModelBuilder modelBuilder)
{
    var entityTypes = modelBuilder.Model.GetEntityTypes();
    foreach (var item in entityTypes)
    {
        var type = item.ClrType;
        var t = XmlDocsExtensions.GetXmlDocsPath(type.Assembly,new());
        var summary = type.GetXmlDocsSummary();
        if (!string.IsNullOrEmpty(summary))
        {
            item.SetComment(summary);
        }

        var typeProperties = type.GetProperties();

        var properties = item.GetProperties();
        foreach (var property in properties)
        {
            summary = typeProperties.FirstOrDefault(a => a.Name == property.Name)
                                    ?.GetXmlDocsSummary();
            if (!string.IsNullOrEmpty(summary))
            {
                property.SetComment(summary);
            }
        }
    }
}

记住,必须启用GenerateDocumentationFile:

<GenerateDocumentationFile>True</GenerateDocumentationFile>

© www.soinside.com 2019 - 2024. All rights reserved.