private void BuildEFContexts(List <TableModel> tables) { StringBuilder builder = new StringBuilder(); builder.AppendLine("using System.Data.Entity; "); builder.AppendLine("using System.Data.Entity.ModelConfiguration.Conventions; "); builder.AppendLine("using System.Linq; "); builder.AppendLine("namespace " + this.DomainName + " "); builder.AppendLine("{ "); builder.AppendLine(" /// <summary> "); builder.AppendLine(" /// 数据上下文 Db" + DbName + "Context "); builder.AppendLine(" /// </summary> "); builder.AppendLine(" public class Db" + DbName + "Context : DbContext "); builder.AppendLine(" { "); builder.AppendLine(" /// <summary> "); builder.AppendLine(" /// 构造函数 "); builder.AppendLine(" /// </summary> "); builder.AppendLine(" public Db" + DbName + "Context() "); builder.AppendLine(" : base(\"" + DbName + "\") "); builder.AppendLine(" { "); builder.AppendLine(" } "); builder.AppendLine("#region 属性 "); for (int i = 0; i < tables.Count; i++) { TableModel tm = tables[i]; string tablename = tm.TableName; string tableInfo = tm.TableNameRemark; builder.AppendLine(" /// <summary> "); builder.AppendLine(" /// " + tableInfo + " "); builder.AppendLine(" /// </summary> "); builder.AppendLine(" public DbSet<" + tablename + "> " + tablename + " { get; set; } "); } builder.AppendLine("#endregion "); builder.AppendLine(" } "); builder.AppendLine(" /// <summary> "); builder.AppendLine(" /// 数据库初始化操作类 "); builder.AppendLine(" /// </summary> "); builder.AppendLine(" public static class DatabaseInitializer "); builder.AppendLine(" { "); builder.AppendLine(" /// <summary> "); builder.AppendLine(" /// 数据库初始化 "); builder.AppendLine(" /// </summary> "); builder.AppendLine(" public static void Initialize() "); builder.AppendLine(" { "); builder.AppendLine(" Database.SetInitializer(new SampleData()); "); builder.AppendLine(" using (var db = new Db" + DbName + "Context()) "); builder.AppendLine(" { "); builder.AppendLine(" db.Database.Initialize(false); "); builder.AppendLine(" } "); builder.AppendLine(" } "); builder.AppendLine(" } "); builder.AppendLine(" /// <summary> "); builder.AppendLine(" /// 数据库初始化策略 "); builder.AppendLine(" /// </summary> "); builder.AppendLine(" public class SampleData : CreateDatabaseIfNotExists<Db" + DbName + "Context> "); builder.AppendLine(" { "); builder.AppendLine(" protected override void Seed(Db" + DbName + "Context context) "); builder.AppendLine(" { "); builder.AppendLine(" "); builder.AppendLine(" //MonitoringArea org = context.Set<MonitoringArea>().Add(new MonitoringArea { PID = 0, Name = \"江西\", X = 0, Y = 0, ImagePath = \"\" }); "); builder.AppendLine(" //context.SaveChanges(); "); builder.AppendLine(" } "); builder.AppendLine(" } "); builder.AppendLine("} "); //写到文件,并加入到项目中。 var file = Path.Combine(Path.GetDirectoryName(EFContexts.get_FileNames(1)), "Db" + DbName) + "Context.cs"; if (!File.Exists(file)) { File.WriteAllText(file, builder.ToString()); EFContexts.ProjectItems.AddFromFile(file); } }