public void CodeFirst(ProjectConfig config) { Initialize(config); StringBuilder sb = new StringBuilder(); List <TableInfo> tables = new List <TableInfo>(); var fileName = config.ContextName + ".dll"; var dir = System.IO.Directory.GetCurrentDirectory(); var providerFile = System.IO.Directory.GetFiles(dir, fileName, SearchOption.AllDirectories).FirstOrDefault(); if (string.IsNullOrEmpty(providerFile)) { throw new FileNotFoundException($"在 {dir} 搜索不到文件 {fileName}"); } var types = Assembly.LoadFrom(providerFile).GetTypes(); List <TableInfo> entitys = new List <TableInfo>(); foreach (var t in types) { var tableAttribute = t.GetCustomAttribute <TableAttribute>(); if (tableAttribute == null) { continue; } entitys.Add(new TableInfo { Name = tableAttribute.Name, Schema = tableAttribute.Schema, EntityType = t }); } foreach (var ent in entitys) { SerializeField(ent, ent.EntityType); var table = Tables.Where(f => f.Schema == ent.Schema && f.Name == ent.Name).FirstOrDefault(); if (table == null) // CREATE { DumpTable(ent, ref sb); } else // ALTER { DumpAlter(ent, table, ref sb); } } // 删除实体 foreach (var table in Tables) { if (entitys.Where(f => f.Schema == table.Schema && f.Name == table.Name).FirstOrDefault() == null) { sb.AppendLine($"DROP TABLE {MyStagingUtils.GetTableName(table, ProviderType.MySql)};"); } } var sql = sb.ToString(); if (string.IsNullOrEmpty(sql)) { Console.WriteLine("数据模型没有可执行的更改."); } else { Console.WriteLine("------------------SQL------------------"); Console.WriteLine(sql); Console.WriteLine("------------------SQL END------------------"); SQLContext.ExecuteNonQuery(CommandType.Text, sql); } }