ArcGIS Pro SDK (八)地理数据库 4 查询
文章目录
- [ArcGIS Pro SDK (八)地理数据库 4 查询](#ArcGIS Pro SDK (八)地理数据库 4 查询)
-
- [1 使用查询筛选器搜索表](#1 使用查询筛选器搜索表)
- [2 在表中搜索非拉丁字符](#2 在表中搜索非拉丁字符)
- [3 使用一组对象 ID 搜索表](#3 使用一组对象 ID 搜索表)
- [4 使用空间查询过滤器搜索要素类](#4 使用空间查询过滤器搜索要素类)
- [5 从表中选择行](#5 从表中选择行)
- [6 从要素类中选择要素](#6 从要素类中选择要素)
- [7 获取表中当前有多少行的计数](#7 获取表中当前有多少行的计数)
- [8 获取图层的特征计数](#8 获取图层的特征计数)
- [9 对表进行排序](#9 对表进行排序)
- [10 计算表的统计信息](#10 计算表的统计信息)
- [11 在单个表上评估 QueryDef](#11 在单个表上评估 QueryDef)
- [12 使用 WHERE 子句计算连接上的 QueryDef](#12 使用 WHERE 子句计算连接上的 QueryDef)
- [13 在外部连接上计算 QueryDef](#13 在外部连接上计算 QueryDef)
- [14 在内部连接上评估 QueryDef](#14 在内部连接上评估 QueryDef)
- [15 在嵌套 - INNER 和 OUTER 连接上评估 QueryDef](#15 在嵌套 - INNER 和 OUTER 连接上评估 QueryDef)
- [16 为数据库表创建默认查询描述并获取查询描述的 ArcGIS.Core.Data.Table](#16 为数据库表创建默认查询描述并获取查询描述的 ArcGIS.Core.Data.Table)
- [17 从数据库表的自定义查询创建查询说明](#17 从数据库表的自定义查询创建查询说明)
- [18 从没有不可为空的唯一 id 列的联接查询创建查询说明](#18 从没有不可为空的唯一 id 列的联接查询创建查询说明)
- [19 从具有多个形状类型的数据库表的查询创建查询说明](#19 从具有多个形状类型的数据库表的查询创建查询说明)
- [20 从 SQLite 数据库表的查询创建查询说明](#20 从 SQLite 数据库表的查询创建查询说明)
- [21 使用 SQLSyntax 形成与平台无关的查询](#21 使用 SQLSyntax 形成与平台无关的查询)
- [22 将文件地理数据库要素类连接到具有虚拟关系类的 Oracle 数据库查询图层要素类](#22 将文件地理数据库要素类连接到具有虚拟关系类的 Oracle 数据库查询图层要素类)
- [23 连接来自不同地理数据库的两个表](#23 连接来自不同地理数据库的两个表)
- [24 使用在地理数据库中连接两个版本化表的查询创建查询表](#24 使用在地理数据库中连接两个版本化表的查询创建查询表)
- [25 检查字段值是否为空](#25 检查字段值是否为空)
- [26 从字段中获取域字符串](#26 从字段中获取域字符串)
环境:Visual Studio 2022 + .NET6 + ArcGIS Pro SDK 3.0
1 使用查询筛选器搜索表
csharp
public async Task SearchingATable()
{
try
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
using (Table table = geodatabase.OpenDataset<Table>("EmployeeInfo"))
{
QueryFilter queryFilter = new QueryFilter
{
WhereClause = "COSTCTRN = 'Information Technology'",
SubFields = "KNOWNAS, OFFICE, LOCATION",
PostfixClause = "ORDER BY OFFICE"
};
using (RowCursor rowCursor = table.Search(queryFilter, false))
{
while (rowCursor.MoveNext())
{
using (Row row = rowCursor.Current)
{
string location = Convert.ToString(row["LOCATION"]);
string knownAs = Convert.ToString(row["KNOWNAS"]);
}
}
}
}
});
}
catch (GeodatabaseFieldException fieldException)
{
// 处理字段异常
}
catch (Exception exception)
{
// 处理其他异常
}
}
2 在表中搜索非拉丁字符
csharp
using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
using (Table table = geodatabase.OpenDataset<Table>("TableWithChineseCharacters"))
{
// 错误的查询示例
string incorrectWhereClause = "颜色 = '绿'";
// 获取国家字符串前缀
string nationalStringPrefix = "";
SQLSyntax sqlSyntax = geodatabase.GetSQLSyntax();
nationalStringPrefix = sqlSyntax.GetSupportedStrings(SQLStringType.NationalStringPrefix).First();
// 正确的查询示例
QueryFilter queryFilter = new QueryFilter()
{
WhereClause = "颜色 = " + nationalStringPrefix + "'绿'"
};
}
3 使用一组对象 ID 搜索表
csharp
public RowCursor SearchingATable(Table table, IReadOnlyList<long> objectIDs)
{
QueryFilter queryFilter = new QueryFilter()
{
ObjectIDs = objectIDs
};
return table.Search(queryFilter);
}
4 使用空间查询过滤器搜索要素类
csharp
public async Task SearchingAFeatureClass()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
using (FeatureClass schoolBoundaryFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.SchoolBoundary"))
{
// 使用空间查询过滤器
SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter
{
WhereClause = "DISTRCTNAME = 'Indian Prairie School District 204'",
FilterGeometry = new PolygonBuilderEx(
new List<Coordinate2D>
{
new Coordinate2D(1021880, 1867396),
new Coordinate2D(1028223, 1870705),
new Coordinate2D(1031165, 1866844),
new Coordinate2D(1025373, 1860501),
new Coordinate2D(1021788, 1863810)
}).ToGeometry(),
SpatialRelationship = SpatialRelationship.Within
};
using (RowCursor indianPrairieCursor = schoolBoundaryFeatureClass.Search(spatialQueryFilter, false))
{
while (indianPrairieCursor.MoveNext())
{
using (Feature feature = (Feature)indianPrairieCursor.Current)
{
// 处理要素
Console.WriteLine(feature.GetObjectID());
}
}
}
}
});
}
5 从表中选择行
csharp
public async Task SelectingRowsFromATable()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
{
QueryFilter anotherQueryFilter = new QueryFilter { WhereClause = "FLOOR = 1 AND WING = 'E'" };
// 选择所有匹配条目
using (Selection anotherSelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.Normal))
{
}
// 选择一个匹配条目
using (Selection onlyOneSelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.OnlyOne))
{
}
// 获取空选择集
using (Selection emptySelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.Empty))
{
}
// 选择表中所有记录
using (Selection allRecordSelection = enterpriseTable.Select(null, SelectionType.ObjectID, SelectionOption.Normal))
{
}
}
});
}
6 从要素类中选择要素
csharp
public async Task SelectingFeaturesFromAFeatureClass()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
{
List<Coordinate2D> newCoordinates = new List<Coordinate2D>
{
new Coordinate2D(1021570, 1880583),
new Coordinate2D(1028730, 1880994),
new Coordinate2D(1029718, 1875644),
new Coordinate2D(1021405, 1875397)
};
SpatialQueryFilter spatialFilter = new SpatialQueryFilter
{
WhereClause = "FCODE = 'Park'",
FilterGeometry = new PolygonBuilderEx(newCoordinates).ToGeometry(),
SpatialRelationship = SpatialRelationship.Crosses
};
// 选择所有匹配条目
using (Selection anotherSelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.Normal))
{
}
// 选择一个匹配条目
using (Selection onlyOneSelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.OnlyOne))
{
}
// 获取空选择集
using (Selection emptySelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.Empty))
{
}
// 选择表中所有记录
using (Selection allRecordSelection = enterpriseFeatureClass.Select(null, SelectionType.ObjectID, SelectionOption.Normal))
{
}
}
});
}
7 获取表中当前有多少行的计数
csharp
// 调用需在 QueuedTask.Run() 内部
var table = featureLayer.GetTable();
var count = table.GetCount();
8 获取图层的特征计数
csharp
var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
QueuedTask.Run(() =>
{
FeatureClass featureClass = lyr.GetFeatureClass();
long nCount = featureClass.GetCount();
});
9 对表进行排序
csharp
public RowCursor SortWorldCities(FeatureClass worldCitiesTable)
{
using (FeatureClassDefinition featureClassDefinition = worldCitiesTable.GetDefinition())
{
Field countryField = featureClassDefinition.GetFields()
.First(x => x.Name.Equals("COUNTRY_NAME"));
Field cityNameField = featureClassDefinition.GetFields()
.First(x => x.Name.Equals("CITY_NAME"));
// 创建国家字段的排序描述
SortDescription countrySortDescription = new SortDescription(countryField);
countrySortDescription.CaseSensitivity = CaseSensitivity.Insensitive;
countrySortDescription.SortOrder = SortOrder.Ascending;
// 创建城市字段的排序描述
SortDescription citySortDescription = new SortDescription(cityNameField);
citySortDescription.CaseSensitivity = CaseSensitivity.Insensitive;
citySortDescription.SortOrder = SortOrder.Ascending;
// 创建表排序描述
TableSortDescription tableSortDescription = new TableSortDescription(
new List<SortDescription>() { countrySortDescription, citySortDescription });
return worldCitiesTable.Sort(tableSortDescription);
}
}
10 计算表的统计信息
csharp
// 计算1990年和2000年人口字段的总和和平均值,并按区域分组和排序
public void CalculateStatistics(FeatureClass countryFeatureClass)
{
using (FeatureClassDefinition featureClassDefinition =
countryFeatureClass.GetDefinition())
{
// 获取字段
Field regionField = featureClassDefinition.GetFields()
.First(x => x.Name.Equals("Region"));
Field pop1990Field = featureClassDefinition.GetFields()
.First(x => x.Name.Equals("Pop1990"));
Field pop2000Field = featureClassDefinition.GetFields()
.First(x => x.Name.Equals("Pop2000"));
// 创建排序描述
SortDescription regionSortDescription = new SortDescription(regionField);
regionSortDescription.CaseSensitivity = CaseSensitivity.Insensitive;
regionSortDescription.SortOrder = SortOrder.Ascending;
TableSortDescription tableSortDescription = new TableSortDescription(
new List<SortDescription>() { regionSortDescription });
// 创建统计描述
TableStatisticsDescription tableStatisticsDescription = new TableStatisticsDescription(
new List<Field>() { pop1990Field, pop2000Field },
new List<StatisticsFunction>() { StatisticsFunction.Sum, StatisticsFunction.Mean },
new List<Field>() { regionField },
tableSortDescription);
// 计算统计信息
using (StatisticsResult statisticsResult =
countryFeatureClass.CalculateStatistics(tableStatisticsDescription))
{
foreach (StatisticsRecord record in statisticsResult)
{
var region = record.GroupBy[0];
var pop1990Sum = record[0];
var pop1990Mean = record[1];
var pop2000Sum = record[2];
var pop2000Mean = record[3];
}
}
}
}
11 在单个表上评估 QueryDef
csharp
public async Task SimpleQueryDef()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
{
QueryDef adaCompliantParksQueryDef = new QueryDef
{
Tables = "Park",
WhereClause = "ADACOMPLY = 'Yes'",
};
using (RowCursor rowCursor = geodatabase.Evaluate(adaCompliantParksQueryDef, false))
{
while (rowCursor.MoveNext())
{
using (Row row = rowCursor.Current)
{
Feature feature = row as Feature;
Geometry shape = feature.GetShape();
String type = Convert.ToString(row["ADACOMPLY"]); // 每行都是 "Yes"
try
{
Table table = row.GetTable(); // 总是抛出异常
}
catch (NotSupportedException exception)
{
// 处理不支持的异常
}
}
}
}
}
});
}
12 使用 WHERE 子句计算连接上的 QueryDef
csharp
public async Task JoiningWithWhereQueryDef()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
{
QueryDef municipalEmergencyFacilitiesQueryDef = new QueryDef
{
SubFields = "EmergencyFacility.OBJECTID, EmergencyFacility.Shape, EmergencyFacility.FACILITYID, FacilitySite.FACILITYID, FacilitySite.FCODE",
Tables = "EmergencyFacility, FacilitySite",
WhereClause = "EmergencyFacility.FACNAME = FacilitySite.NAME AND EmergencyFacility.JURISDICT = 'Municipal'",
};
using (RowCursor rowCursor = geodatabase.Evaluate(municipalEmergencyFacilitiesQueryDef, false))
{
while (rowCursor.MoveNext())
{
using (Row row = rowCursor.Current)
{
Feature feature = row as Feature;
Geometry shape = feature.GetShape();
long objectID = Convert.ToInt64(row["EmergencyFacility.OBJECTID"]);
String featureCode = Convert.ToString(row["FacilitySite.FCODE"]);
IReadOnlyList<Field> fields = feature.GetFields(); // 每个子字段包含一个 ArcGIS.Core.Data.Field 对象
}
}
}
}
});
}
13 在外部连接上计算 QueryDef
csharp
public async Task EvaluatingQueryDefWithOuterJoin()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
{
QueryDef queryDefWithLeftOuterJoin = new QueryDef
{
Tables = "CommunityAddress LEFT OUTER JOIN MunicipalBoundary on CommunityAddress.Municipality = MunicipalBoundary.Name",
SubFields = "CommunityAddress.OBJECTID, CommunityAddress.Shape, CommunityAddress.SITEADDID, CommunityAddress.ADDRNUM, CommunityAddress.FULLNAME, CommunityAddress.FULLADDR, CommunityAddress.MUNICIPALITY, MunicipalBoundary.Name, MunicipalBoundary.MUNITYP, MunicipalBoundary.LOCALFIPS",
};
using (RowCursor rowCursor = geodatabase.Evaluate(queryDefWithLeftOuterJoin, false))
{
while (rowCursor.MoveNext())
{
using (Row row = rowCursor.Current)
{
Feature feature = row as Feature;
Geometry shape = feature.GetShape();
int siteAddressId = Convert.ToInt32(row["CommunityAddress.SITEADDID"]);
String stateName = Convert.ToString(row["MunicipalBoundary.name"]);
}
}
}
}
});
}
14 在内部连接上评估 QueryDef
csharp
public async Task EvaluatingQueryDefWithInnerJoin()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
{
QueryDef queryDef = new QueryDef()
{
Tables = "People INNER JOIN States ON People.FK_STATE_ID = States.OBJECTID",
SubFields = "People.OBJECTID, People.First_Name, People.Last_Name, People.City, States.State_Name"
};
using (RowCursor cursor = geodatabase.Evaluate(queryDef))
{
while (cursor.MoveNext())
{
using (Row row = cursor.Current)
{
// 处理行
}
}
}
}
});
}
15 在嵌套 - INNER 和 OUTER 连接上评估 QueryDef
csharp
public async Task EvaluatingQueryDefWithNestedJoin()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(
new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
{
QueryDef queryDef = new QueryDef()
{
Tables = "((People INNER JOIN States ON People.FK_STATE_ID = States.OBJECTID) LEFT OUTER JOIN Homes ON People.OBJECTID = Homes.FK_People_ID)",
SubFields = "People.OBJECTID, People.First_Name, People.Last_Name, States.State_Name, Homes.Address"
};
using (RowCursor cursor = geodatabase.Evaluate(queryDef, false))
{
while (cursor.MoveNext())
{
using (Row row = cursor.Current)
{
// 处理行
}
}
}
}
});
}
16 为数据库表创建默认查询描述并获取查询描述的 ArcGIS.Core.Data.Table
csharp
public async Task DefaultQueryDescription()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
DatabaseConnectionProperties databaseConnectionProperties =
new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
{
AuthenticationMode = AuthenticationMode.DBMS,
Instance = "instance",
Database = "database",
User = "user",
Password = "password"
};
using (Database database = new Database(databaseConnectionProperties))
{
QueryDescription queryDescription = database.GetQueryDescription("CUSTOMERS");
using (Table table = database.OpenTable(queryDescription))
{
// 使用表
}
}
});
}
17 从数据库表的自定义查询创建查询说明
csharp
public async Task CustomQueryDescription()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
DatabaseConnectionProperties databaseConnectionProperties =
new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
{
AuthenticationMode = AuthenticationMode.DBMS,
Instance = "instance",
Database = "database",
User = "user",
Password = "password"
};
using (Database database = new Database(databaseConnectionProperties))
{
QueryDescription queryDescription = database.GetQueryDescription("SELECT OBJECTID, Shape, FACILITYID FROM EmergencyFacility WHERE JURISDICT = 'Municipal'", "MunicipalEmergencyFacilities");
using (Table table = database.OpenTable(queryDescription))
{
// 使用表.
}
}
});
}
18 从没有不可为空的唯一 id 列的联接查询创建查询说明
csharp
public async Task JoinQueryDescription()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
DatabaseConnectionProperties databaseConnectionProperties =
new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
{
AuthenticationMode = AuthenticationMode.DBMS,
Instance = "instance",
Database = "database",
User = "user",
Password = "password"
};
using (Database database = new Database(databaseConnectionProperties))
{
QueryDescription queryDescription = database.GetQueryDescription("SELECT BUSLINES.ID as BUSLINESID, BUSSTOPS.ID as BUSSTOPSID, BUSLINES.RTE_DESC, BUSLINES.DIR, BUSSTOPS.JURISDIC, BUSSTOPS.LOCATION, BUSSTOPS.ROUTE,BUSSTOPS.SHAPE from demosql.dbo.BUSSTOPS JOIN demosql.dbo.BUSLINES ON BUSSTOPS.ROUTE = BUSLINES.ROUTE", "BusInfo");
queryDescription.SetObjectIDFields("BUSLINESID,BUSSTOPSID");
using (Table table = database.OpenTable(queryDescription))
{
// 使用表.
}
}
});
}
19 从具有多个形状类型的数据库表的查询创建查询说明
csharp
public async Task MultiGeometryQueryDescription()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
DatabaseConnectionProperties databaseConnectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
{
AuthenticationMode = AuthenticationMode.DBMS,
Instance = "instance",
Database = "database",
User = "user",
Password = "password"
};
using (Database database = new Database(databaseConnectionProperties))
{
QueryDescription pointQueryDescription = database.GetQueryDescription("SELECT * FROM POINTS", "PointLayer");
QueryDescription lineQueryDescription = database.GetQueryDescription("SELECT * FROM LINES", "LineLayer");
using (Table pointTable = database.OpenTable(pointQueryDescription))
{
// 使用点表.
}
using (Table lineTable = database.OpenTable(lineQueryDescription))
{
// 使用线表.
}
}
});
}
20 从 SQLite 数据库表的查询创建查询说明
csharp
public async Task SqliteQueryDescription()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Database database = new Database(new SQLiteConnectionPath(new Uri("Path\\To\\Sqlite\\Database\\USA.sqlite"))))
{
QueryDescription washingtonCitiesQueryDescription = database.GetQueryDescription("select OBJECTID, Shape, CITY_FIPS, CITY_NAME, STATE_FIPS, STATE_CITY, TYPE, CAPITAL from main.cities where STATE_NAME='Washington'", "WashingtonCities");
using (Table washingtonTable = database.OpenTable(washingtonCitiesQueryDescription))
{
// 使用washingtonTable。
}
}
});
}
21 使用 SQLSyntax 形成与平台无关的查询
csharp
public async Task UsingSqlSyntaxToFormPlatformAgnosticQueries()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("C:\\Data\\LocalGovernment.gdb"))))
using (FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>("FacilitySite"))
{
SQLSyntax sqlSyntax = geodatabase.GetSQLSyntax();
string substringFunctionName = sqlSyntax.GetFunctionName(SQLFunction.Substring);
string upperFunctionName = sqlSyntax.GetFunctionName(SQLFunction.Upper);
string substringfunction = string.Format("{0}({1}(FCODE, 1, 6)) = 'SCHOOL'", upperFunctionName, substringFunctionName);
QueryFilter queryFilter = new QueryFilter
{
WhereClause = substringfunction
};
using (Selection selection = featureClass.Select(queryFilter, SelectionType.ObjectID, SelectionOption.Normal))
{
// 使用选择结果。
}
}
});
}
22 将文件地理数据库要素类连接到具有虚拟关系类的 Oracle 数据库查询图层要素类
csharp
public async Task JoiningFileGeodatabaseFeatureClassToOracleQueryLayer()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("C:\\Data\\LocalGovernment.gdb"))))
using (Database database = new Database(
new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle)
{
AuthenticationMode = AuthenticationMode.DBMS,
Instance = "instance",
User = "user",
Password = "password",
Database = "database"
}))
using (FeatureClass leftFeatureClass = geodatabase.OpenDataset<FeatureClass>("Hospital"))
using (Table rightTable = database.OpenTable(database.GetQueryDescription("FacilitySite")))
{
Field originPrimaryKey = leftFeatureClass.GetDefinition().GetFields().FirstOrDefault(field => field.Name.Equals("facilityId"));
Field destinationForeignKey = rightTable.GetDefinition().GetFields().FirstOrDefault(field => field.Name.Equals("hospitalID"));
VirtualRelationshipClassDescription description =
new VirtualRelationshipClassDescription(
originPrimaryKey, destinationForeignKey, RelationshipCardinality.OneToOne);
using (RelationshipClass relationshipClass = leftFeatureClass.RelateTo(rightTable, description))
{
JoinDescription joinDescription = new JoinDescription(relationshipClass)
{
JoinDirection = JoinDirection.Forward,
JoinType = JoinType.LeftOuterJoin
};
Join join = new Join(joinDescription);
using (Table joinedTable = join.GetJoinedTable())
{
// 对连接后的表执行操作。
}
}
}
});
}
23 连接来自不同地理数据库的两个表
csharp
public async Task JoinTablesFromDifferentGeodatabases()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
using (Geodatabase sourceGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("Path \\ to \\Geodatabase \\ one"))))
using (Geodatabase destinationGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("Path \\ to \\Geodatabase \\ two"))))
using (Table sourceTable = sourceGeodatabase.OpenDataset<Table>("State"))
using (Table destinationTable = destinationGeodatabase.OpenDataset<Table>("Cities"))
{
Field primaryKeyField = sourceTable.GetDefinition().GetFields().FirstOrDefault(field => field.Name.Equals("State.State_Abbreviation"));
Field foreignKeyField = destinationTable.GetDefinition().GetFields().FirstOrDefault(field => field.Name.Equals("Cities.State"));
VirtualRelationshipClassDescription virtualRelationshipClassDescription = new VirtualRelationshipClassDescription(primaryKeyField, foreignKeyField, RelationshipCardinality.OneToMany);
using (RelationshipClass relationshipClass = sourceTable.RelateTo(destinationTable, virtualRelationshipClassDescription))
{
JoinDescription joinDescription = new JoinDescription(relationshipClass)
{
JoinDirection = JoinDirection.Forward,
JoinType = JoinType.InnerJoin,
TargetFields = sourceTable.GetDefinition().GetFields()
};
using (Join join = new Join(joinDescription))
{
Table joinedTable = join.GetJoinedTable();
//处理连接后的表。例如 ..
using (RowCursor cursor = joinedTable.Search())
{
while (cursor.MoveNext())
{
using (Row row = cursor.Current)
{
// 使用行数据。
}
}
}
}
}
}
});
}
24 使用在地理数据库中连接两个版本化表的查询创建查询表
csharp
public async Task QueryTableJoinWithVersionedData()
{
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(
() =>
{
QueryDef queryDef = new QueryDef
{
Tables = "CommunityAddress JOIN MunicipalBoundary on CommunityAddress.Municipality = MunicipalBoundary.Name",
SubFields = "CommunityAddress.OBJECTID, CommunityAddress.Shape, CommunityAddress.SITEADDID, CommunityAddress.ADDRNUM, CommunityAddress.FULLNAME, CommunityAddress.FULLADDR, CommunityAddress.MUNICIPALITY, MunicipalBoundary.Name, MunicipalBoundary.MUNITYP, MunicipalBoundary.LOCALFIPS",
};
using (Geodatabase testVersion1Geodatabase = new Geodatabase(
new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle)
{
AuthenticationMode = AuthenticationMode.DBMS,
Instance = "instance",
User = "user",
Password = "password",
Database = "database",
Version = "user.testVersion1"
}))
{
QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef)
{
Name = "CommunityAddrJounMunicipalBoundr",
PrimaryKeys = testVersion1Geodatabase.GetSQLSyntax().QualifyColumnName("CommunityAddress", "OBJECTID")
};
// 将基于testVersion1。
using (Table queryTable = testVersion1Geodatabase.OpenQueryTable(queryTableDescription))
{
// 使用queryTable。
}
}
using (Geodatabase testVersion2Geodatabase = new Geodatabase(
new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle)
{
AuthenticationMode = AuthenticationMode.DBMS,
Instance = "instance",
User = "user",
Password = "password",
Database = "database",
Version = "user.testVersion2"
}))
{
QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef)
{
Name = "CommunityAddrJounMunicipalBoundr",
PrimaryKeys = testVersion2Geodatabase.GetSQLSyntax().QualifyColumnName("CommunityAddress", "OBJECTID")
};
// 将基于testVersion2。
using (Table queryTable = testVersion2Geodatabase.OpenQueryTable(queryTableDescription))
{
// 使用queryTable。
}
}
});
}
25 检查字段值是否为空
csharp
var val = row[field.Name];
if (val is DBNull || val == null)
{
// 字段值为空
}
else
{
// 字段值不为空
}
26 从字段中获取域字符串
csharp
public string GetDomainStringFromField(Row row, Field field)
{
// 从Row中获取表和表定义
using (Table table = row.GetTable())
using (TableDefinition tableDefinition = table.GetDefinition())
{
// 获取子类型字段的名称
string subtypeFieldName = tableDefinition.GetSubtypeField();
// 获取子类型,如果有的话
Subtype subtype = null;
if (subtypeFieldName.Length != 0)
{
// 获取此行的子类型字段的值
var varSubtypeCode = row[subtypeFieldName];
long subtypeCode = (long)varSubtypeCode;
// 获取此行的子类型
subtype = tableDefinition.GetSubtypes().First(x => x.GetCode() == subtypeCode);
}
// 获取此字段的编码值域
CodedValueDomain domain = field.GetDomain(subtype) as CodedValueDomain;
// 返回此字段的文本字符串
if (domain != null)
{
return domain.GetName(row[field.Name]);
}
else
{
return row[field.Name].ToString();
}
}
}