先看一眼代码:
using System; using System.Collections.Generic; using XCode; using XCode.Configuration; using XCode.DataAccessLayer; namespace RandomInsert { internal class Program { private static int NeedCount = 10000; private static void Main(string[] args) { Console.WriteLine("开始"); FillDataForDb("demo"); Console.WriteLine("完成"); } /// <summary> /// 随机填充指定数据库连接字符串中的所有表 /// </summary> /// <param name="connStr">数据库连接字符串</param> public static void FillDataForDb(string connStr) { DAL dal = DAL.Create(connStr);//根据数据库连接字符串创建数据访问对象 List<IDataTable> tableList = dal.Tables;//获取数据库的所有表和架构信息 if (tableList == null) { Console.WriteLine("没有表结构"); return; } tableList.RemoveAll(t => t.IsView);//过滤掉视图 foreach (var item in tableList) { //首先根据表名称获取当前表的实体操作接口 IEntityOperate entity = dal.CreateOperate(item.Name); //entity.BeginTransaction();事务暂时不启用 for (int i = 0; i < NeedCount; i++) { if (i % 1000 == 0) { Console.WriteLine("{0}{1}", item.TableName, i); } IEntity model = entity.Create();//创建数据实体接口 //entity.Fields获取所有的字段信息 foreach (var fild in entity.Fields) { if (!fild.IsIdentity) model.SetItem(fild.Name, GetRandomValue(fild)); } model.Save();//保存数据 } //entity.Commit(); } } /// <summary> /// 根据字段类型和长度获取对应类型的随机数据 /// </summary> /// <param name="fild">字段对象</param> /// <returns>对应的随机数据</returns> public static object GetRandomValue(FieldItem fild) { switch (Type.GetTypeCode(fild.Field.DataType)) { case TypeCode.Boolean: return RandomHelper.GetRandomBool(); case TypeCode.Byte: return RandomHelper.GetRandomByte(); case TypeCode.Char: return RandomHelper.GetRandomChar(); case TypeCode.DateTime: return RandomHelper.GetRandomDateTime(); case TypeCode.Decimal: return RandomHelper.GetRandomDouble(0, NeedCount * 10.1); case TypeCode.Double: return RandomHelper.GetRandomDouble(0, NeedCount * 10.1); case TypeCode.Int16: return RandomHelper.GetRandomInt(1, int.MaxValue); case TypeCode.Int32: return RandomHelper.GetRandomInt(1, NeedCount * 50); case TypeCode.Int64: return RandomHelper.GetRandomInt(1, NeedCount * 100); case TypeCode.SByte: return RandomHelper.GetRandomInt(1, 127); case TypeCode.Single: return RandomHelper.GetRandomDouble(0, NeedCount * 10.1); case TypeCode.String: return RandomHelper.GetRandomString((int)(fild.Length * RandomHelper.GetRandomDouble(0.2, 0.7))); case TypeCode.UInt16: return RandomHelper.GetRandomInt(int.MinValue, int.MaxValue); case TypeCode.UInt32: return RandomHelper.GetRandomInt(1, NeedCount * 50); case TypeCode.UInt64: return RandomHelper.GetRandomInt(1, NeedCount * 100); case TypeCode.Empty: case TypeCode.Object: case TypeCode.DBNull: return string.Empty; default: return string.Empty; } } } }
本段代码由大石头提供技术支持,小董原创,老邱完成,ha666抄过来。
VS2013Update5就有“性能和诊断”功能了
选择“调试”菜单->“性能和诊断”
欢迎加QQ群(1600800)讨论。
时间: 2024-12-19 06:00:52