protected override void Seed(Context context) { base.Seed(context); Seeding.Seed(context); }
public void InitializeDatabase(Context context) { if (System.Diagnostics.Debugger.IsAttached && context.Database.Exists()) //&& !context.Database.CompatibleWithModel(false)) { context.Database.Delete(); } if (!context.Database.Exists()) { context.Database.Create(); Seeding.Seed(context); var contextObject = context as System.Object; var contextType = contextObject.GetType(); var properties = contextType.GetProperties(); System.Type t = null; string tableName = null; string fieldName = null; foreach (var pi in properties) { if (pi.PropertyType.IsGenericType && pi.PropertyType.Name.Contains("DbSet")) { t = pi.PropertyType.GetGenericArguments()[0]; var mytableName = t.GetCustomAttributes(typeof(DisplayNameAttribute), true); if (mytableName.Length > 0) { DisplayNameAttribute mytable = mytableName[0] as DisplayNameAttribute; // tableName = mytable.Name; } else { tableName = pi.Name; // EXECUTE sp_addextendedproperty N'MS_Description', '销售套餐1', N'user', N'dbo', N'table', N'SalePackages' } FieldInfo tableNameField = t.GetField("LogClass"); string descTable = tableName; if (tableNameField != null) { descTable = tableNameField.GetValue(t) + ""; } ///0 tablename string dropTableDesc = " EXEC sp_dropextendedproperty 'MS_Description','user',dbo,'table','{0}' "; ///0 tabledesc,1 tablename string addTableDesc = " EXECUTE sp_addextendedproperty N'MS_Description', '{0}', N'user', N'dbo', N'table', N'{1}'"; try { context.Database.ExecuteSqlCommand(string.Format(dropTableDesc, tableName)); } catch { } try { context.Database.ExecuteSqlCommand(string.Format(addTableDesc, descTable, tableName)); } catch { } // string descTableName = pi.get // t.GetProperty("LogClass"); foreach (var piEntity in t.GetProperties()) { if (piEntity.GetCustomAttributes(typeof(DisplayNameAttribute), true).Length > 0) { fieldName = piEntity.Name; //EXEC sp_dropextendedproperty 'MS_Description','user',dbo,'table','Clients','column',N'SalesId'; //EXEC sp_addextendedproperty N'MS_Description','自动编号1',N'user',N'dbo',N'table',N'Clients',N'column',N'SalesId' //说明文字先后顺序,先description -> displayname string desc = ((DisplayNameAttribute)piEntity.GetCustomAttributes(typeof(DisplayNameAttribute), true)[0]).DisplayName; if (piEntity.GetCustomAttributes(typeof(DescriptionAttribute), true).Length > 0) { desc = ((DescriptionAttribute)piEntity.GetCustomAttributes(typeof(DescriptionAttribute), true)[0]).Description; } //0 tablename,1 columnname,2 desc string dropdesc = string.Format("EXEC sp_dropextendedproperty 'MS_Description','user',dbo,'table','{0}','column',N'{1}'", tableName, fieldName); string createdesc = string.Format("EXEC sp_addextendedproperty N'MS_Description','{2}',N'user',N'dbo',N'table',N'{0}',N'column',N'{1}'", tableName, fieldName, desc); try { context.Database.ExecuteSqlCommand(dropdesc); } catch { } try { context.Database.ExecuteSqlCommand(createdesc); } catch { } } } } } } }