无论是linq to sql 还是entity frameworks,在进行列表操作时都会有一个毛病,那就是它的操作只能一个实体一个实体的发到服务器,这样,如果列表的数量很大,如列表为10万条数据,那么,这种操作将是非常性能的,可能你的DB就挂了。
解决方案:拼接T—SQL串,并使它具有通用性
好处:与服务器建立一次连接,给服务器发一条SQL命令,即可实现
代码如下:
1 /// 2 /// 构建Insert语句串 3 /// 主键为自增时,如果主键值为0,我们将主键插入到SQL串中 4 /// 5 /// 6 /// 7 /// 8 private Tuple CreateInsertSQL (TEntity entity) where TEntity : class 9 {10 if (entity == null)11 throw new ArgumentException("The database entity can not be null.");12 13 Type entityType = entity.GetType();14 var table = entityType.GetProperties().Where(i => i.PropertyType != typeof(EntityKey)15 && i.PropertyType != typeof(EntityState)16 && i.GetValue(entity, null) != null17 && (i.PropertyType.IsValueType || i.PropertyType == typeof(string)))18 .ToArray();//过滤主键,航行属性,状态属性等19 List pkList = GetPrimaryKey ().Select(i => i.Name).ToList();20 21 List
之后我将陆续把更新操作与删除操作及对增删改操作进行封装,献给大家,尽请期待。