增删实体是CAD二次开发最常见的操作,本文封装了4个最通用的实体增删函数。
添加单个实体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public static ObjectId AddEntity(this Database db, Entity entity, string layoutName = null){ if (entity == null) return ObjectId.Null;
ObjectId id = ObjectId.Null; using (var docLock = DwgOperators.ThisDocument.LockDocument()) { using (Transaction transaction = db.TransactionManager.StartTransaction()) { BlockTable bt = transaction.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; bool flag = true; ObjectId spaceId = ObjectId.Null; if (layoutName == null) spaceId = bt[BlockTableRecord.ModelSpace]; else { spaceId = GetLayoutIdByName(db, layoutName); if (spaceId == ObjectId.Null) flag = false; } if (flag) { BlockTableRecord btr = transaction.GetObject(spaceId, OpenMode.ForWrite) as BlockTableRecord; id = btr.AppendEntity(entity); transaction.AddNewlyCreatedDBObject(entity, true); } transaction.Commit(); } return id; } }
|
添加多个实体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public static List<ObjectId> AddEntities<T>(this Database db, List<T> entities, string layoutName = null) where T : Entity { List<ObjectId> ids = new List<ObjectId>(); ObjectId id = ObjectId.Null; using (Transaction transaction = db.TransactionManager.StartTransaction()) { BlockTable bt = transaction.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
bool flag = true; ObjectId spaceId = ObjectId.Null; if (layoutName == null) spaceId = bt[BlockTableRecord.ModelSpace]; else { spaceId = GetLayoutIdByName(db, layoutName); if (spaceId == ObjectId.Null) flag = false; }
if (flag) { BlockTableRecord btr = transaction.GetObject(spaceId, OpenMode.ForWrite) as BlockTableRecord; foreach (Entity entity in entities) { id = btr.AppendEntity(entity); transaction.AddNewlyCreatedDBObject(entity, true); ids.Add(id); } } transaction.Commit(); } return ids; }
|
删除单个实体
1 2 3 4 5 6 7 8 9 10 11
| public static void DeleteEntity(this Database db, ObjectId id) { if (id == ObjectId.Null) return; using (Transaction transaction = db.TransactionManager.StartTransaction()) { var entity = transaction.GetObject(id, OpenMode.ForWrite, true); if (entity != null) entity.Erase(true); transaction.Commit(); } }
|
删除多个实体
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public static void DeleteEntities(this Database db, params ObjectId[] ids) { if (ids == null || ids.Count() == 0) return; using (Transaction transaction = db.TransactionManager.StartTransaction()) { foreach (ObjectId id in ids) { var entity = transaction.GetObject(id, OpenMode.ForWrite, true); if (entity != null) entity.Erase(true); } transaction.Commit(); } }
|