在我们的项目中经常采用model first这种方式先来设计数据库model,然后通过migration来生成数据库表结构,有些时候我们需要动态通过实体model来创建数据库的表结构,特别是在创建像临时表这一类型的时候,我们直接通过代码来进行创建就可以了不用通过创建实体然后迁移这种方式来进行,其实原理也很简单就是通过遍历当前model然后获取每一个属性并以此来生成部分创建脚本,然后将这些创建的脚本拼接成一个完整的脚本到数据库中去执行就可以了,只不过这里有一些需要注意的地方,下面我们来通过代码来一步步分析怎么进行这些代码规范编写以及需要注意些什么问题。

  一  代码分析

/// <summary>
    /// model 生成数据库表脚本
    /// </summary>
    public class tablegenerator : itablegenerator {
        private static dictionary<type, string> datamapper {
            get {
                var datamapper = new dictionary<type, string> {
                    {typeof(int), "number(10) not null"},
                    {typeof(int?), "number(10)"},
                    {typeof(string), "varchar2({0} char)"},
                    {typeof(bool), "number(1)"},
                    {typeof(datetime), "date"},
                    {typeof(datetime?), "date"},
                    {typeof(float), "float"},
                    {typeof(float?), "float"},
                    {typeof(decimal), "decimal(16,4)"},
                    {typeof(decimal?), "decimal(16,4)"},
                    {typeof(guid), "char(36)"},
                    {typeof(guid?), "char(36)"}
                };
 
                return datamapper;
            }
        }
 
        private readonly list<keyvaluepair<string, propertyinfo>> _fields = new list<keyvaluepair<string, propertyinfo>>();
 
        /// <summary>
        ///
        /// </summary>
        private string _tablename;
 
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private string gettablename(memberinfo entitytype) {
            if (_tablename != null)
                return _tablename;
            var prefix = entitytype.getcustomattribute<temptableattribute>() != null ? "#" : string.empty;
            return _tablename = $"{prefix}{entitytype.getcustomattribute<tableattribute>()?.name ?? entitytype.name}";
        }
 
        /// <summary>
        /// 生成创建表的脚本
        /// </summary>
        /// <returns></returns>
        public string generatetablescript(type entitytype) {
            if (entitytype == null)
                throw new argumentnullexception(nameof(entitytype));
 
            generatefields(entitytype);
 
            const int defaultcolumnlength = 500;
            var script = new stringbuilder();
 
            script.appendline($"create table {gettablename(entitytype)} (");
            foreach (var (propname, propertyinfo) in _fields) {
                if (!datamapper.containskey(propertyinfo.propertytype))
                    throw new notsupportedexception($"尚不支持 {propertyinfo.propertytype}, 请联系开发人员.");
                if (propertyinfo.propertytype == typeof(string)) {
                    var maxlengthattribute = propertyinfo.getcustomattribute<maxlengthattribute>();
                    script.append($"\t {propname} {string.format(datamapper[propertyinfo.propertytype], maxlengthattribute?.length ?? defaultcolumnlength)}");
                    if (propertyinfo.getcustomattribute<requiredattribute>() != null)
                        script.append(" not null");
                    script.appendline(",");
                } else {
                    script.appendline($"\t {propname} {datamapper[propertyinfo.propertytype]},");
                }
            }
 
            script.remove(script.length - 1, 1);
 
            script.appendline(")");
 
            return script.tostring();
        }
 
        private void generatefields(type entitytype) {
            foreach (var p in entitytype.getproperties()) {
                if (p.getcustomattribute<notmappedattribute>() != null)
                    continue;
                var columnname = p.getcustomattribute<columnattribute>()?.name ?? p.name;
                var field = new keyvaluepair<string, propertyinfo>(columnname, p);
                _fields.add(field);
            }
        }
    }

  这里的tablegenerator继承自接口itablegenerator,在这个接口内部只定义了一个 string generatetablescript(type entitytype) 方法。

/// <summary>
    /// model 生成数据库表脚本
    /// </summary>
    public interface itablegenerator {
        /// <summary>
        /// 生成创建表的脚本
        /// </summary>
        /// <returns></returns>
        string generatetablescript(type entitytype);
    }

  这里我们来一步步分析这些部分的含义,这个里面datamapper主要是用来定义一些c#基础数据类型和数据库生成脚本之间的映射关系。

     1  gettablename

  接下来我们看看gettablename这个函数,这里首先来当前model是否定义了temptableattribute,这个看名字就清楚了就是用来定义当前model是否是用来生成一张临时表的。

/// <summary>
    /// 是否临时表, 仅限 dapper 生成 数据库表结构时使用
    /// </summary>
    [attributeusage(attributetargets.class | attributetargets.struct)]
    public class temptableattribute : attribute {
 
    }

  具体我们来看看怎样在实体model中定义temptableattribute这个自定义属性。

[temptable]
      class stringtable {
          public string defaultstring { get; set; }
          [maxlength(30)]
          public string lengthstring { get; set; }
          [required]
          public string notnullstring { get; set; }
      }

  就像这样定义的话,我们就知道当前model会生成一张sql server的临时表。

  当然如果是生成临时表,则会在生成的表名称前面加一个‘#’标志,在这段代码中我们还会去判断当前实体是否定义了tableattribute,如果定义过就去取这个tableattribute的名称,否则就去当前model的名称,这里也举一个实例。

[table("test")]
       class inttable {
           public int intproperty { get; set; }
           public int? nullableintproperty { get; set; }
       }

  这样我们通过代码创建的数据库名称就是test啦。

     2  generatefields

  这个主要是用来一个个读取model中的属性,并将每一个实体属性整理成一个keyvaluepair<string, propertyinfo>的对象从而方便最后一步来生成整个表完整的脚本,这里也有些内容需要注意,如果当前属性定义了notmappedattribute标签,那么我们可以直接跳过当前属性,另外还需要注意的地方就是当前属性的名称首先看当前属性是否定义了columnattribute的如果定义了,那么数据库中字段名称就取自columnattribute定义的名称,否则才是取自当前属性的名称,通过这样一步操作我们就能够将所有的属性读取到一个自定义的数据结构list<keyvaluepair<string, propertyinfo>>里面去了。

     3  generatetablescript

  有了前面的两步准备工作,后面就是进入到生成整个创建表脚本的部分了,其实这里也比较简单,就是通过循环来一个个生成每一个属性对应的脚本,然后通过stringbuilder来拼接到一起形成一个完整的整体。这里面有一点需要我们注意的地方就是当前字段是否可为空还取决于当前属性是否定义过requiredattribute标签,如果定义过那么就需要在创建的脚本后面添加not null,最后一个重点就是对于string类型的属性我们需要读取其定义的maxlength属性从而确定数据库中的字段长度,如果没有定义则取默认长度500。

  当然一个完整的代码怎么能少得了单元测试呢?下面我们来看看单元测试。

  二  单元测试

public class sqlservertablegenerator_tests {
       [table("test")]
       class inttable {
           public int intproperty { get; set; }
           public int? nullableintproperty { get; set; }
       }
 
       [fact]
       public void generatetablescript_int_number10() {
           // act
           var sql = new tablegenerator().generatetablescript(typeof(inttable));
           // assert
           sql.shouldcontain("intproperty number(10) not null");
           sql.shouldcontain("nullableintproperty number(10)");
       }
 
       [fact]
       public void generatetablescript_testtablename_test() {
           // act
           var sql = new tablegenerator().generatetablescript(typeof(inttable));
           // assert
           sql.shouldcontain("create table test");
       }
 
       [temptable]
       class stringtable {
           public string defaultstring { get; set; }
           [maxlength(30)]
           public string lengthstring { get; set; }
           [required]
           public string notnullstring { get; set; }
       }
 
       [fact]
       public void generatetablescript_temptable_tablenamewithsharp() {
           // act
           var sql = new tablegenerator().generatetablescript(typeof(stringtable));
           // assert
           sql.shouldcontain("create table #stringtable");
       }
 
       [fact]
       public void generatetablescript_string_varchar() {
           // act
           var sql = new tablegenerator().generatetablescript(typeof(stringtable));
           // assert
           sql.shouldcontain("defaultstring varchar2(500 char)");
           sql.shouldcontain("lengthstring varchar2(30 char)");
           sql.shouldcontain("notnullstring varchar2(500 char) not null");
       }
 
       class columntable {
           [column("test")]
           public int intproperty { get; set; }
           [notmapped]
           public int ingored {get; set; }
       }
 
       [fact]
       public void generatetablescript_columnname_newname() {
           // act
           var sql = new tablegenerator().generatetablescript(typeof(columntable));
           // assert
           sql.shouldcontain("test number(10) not null");
       }
 
       [fact]
       public void generatetablescript_notmapped_ignore() {
           // act
           var sql = new tablegenerator().generatetablescript(typeof(columntable));
           // assert
           sql.shouldnotcontain("ingored number(10) not null");
       }
 
       class notsupportedtable {
           public dynamic ingored {get; set; }
       }
 
       [fact]
       public void generatetablescript_notsupported_throwexception() {
           // act
           assert.throws<notsupportedexception>(() => {
               new tablegenerator().generatetablescript(typeof(notsupportedtable));
           });
       }
   }

  最后我们来看看最终生成的创建表的脚本。

          1  定义过tableattribute的脚本。

create table test (
     intproperty number(10) not null,
     nullableintproperty number(10),
)

          2  生成的临时表的脚本。

create table #stringtable (
     defaultstring varchar2(500 char),
     lengthstring varchar2(30 char),
     notnullstring varchar2(500 char) not null,
)

  通过这种方式我们就能够在代码中去动态生成数据库表结构了。

以上就是efcore 通过实体model生成创建sql server数据库表脚本的详细内容,更多关于efcore 创建sql server数据库表脚本的资料请关注www.887551.com其它相关文章!