温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在EFCore中与实体Model生成一个SQL Server数据库脚本

发布时间:2021-03-04 14:23:48 来源:亿速云 阅读:223 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关如何在EFCore中与实体Model生成一个SQL Server数据库脚本,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

  一  代码分析

/// <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数据库脚本了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI