Query Related Tables

Download Samples Repository

Description

This sample demonstrates how to use a relationship query to display information from a related table for selected features. Clicking on the map highlight a set of wells near the clicked point. Select a well from the list to display related features (tops). The object id of the well is used in the relationship query to return 0 to many related records displayed in the list view. Note that the code requires a relationshipId. Feature layers can have more than one relationship and each relationship is identified by a unique identifier. You can use the Services Directory to find the relationship id.

"Desktop" "Store" "Phone" Available for Desktop, Store, Phone

Sample Code

<UserControl x:Class="ArcGISRuntime.Samples.Desktop.QueryRelatedTables"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013">
    <Grid x:Name="layoutGrid">
        <Grid.Resources>
            <esri:SimpleMarkerSymbol x:Key="DefaultMarkerSymbol" Style="Circle" Size="14" Color="Red" />
            <esri:SimpleRenderer x:Key="SimpleRenderer" Symbol="{StaticResource DefaultMarkerSymbol}" />
        </Grid.Resources>

        <esri:MapView x:Name="MyMapView" MapViewTapped="MyMapView_MapViewTapped">
			<esri:Map InitialViewpoint="-10854000, 4502000, -10829000, 4524000, 3857">
                <esri:ArcGISTiledMapServiceLayer 
                    ServiceUri="http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer" />
                <esri:ArcGISDynamicMapServiceLayer
                    ServiceUri="http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Petroleum/KSPetro/MapServer" />
            </esri:Map>
			<esri:MapView.GraphicsOverlays>
				<esri:GraphicsOverlay ID="wellsOverlay" Renderer="{StaticResource SimpleRenderer}" />
			</esri:MapView.GraphicsOverlays>
        </esri:MapView>

		<Border x:Name="resultsPanel" Margin="5" Padding="5"
                Background="#77919191" BorderBrush="Black" BorderThickness="1" 
                HorizontalAlignment="Right" VerticalAlignment="Bottom"
                Visibility="Collapsed">
			<Grid HorizontalAlignment="Right" VerticalAlignment="Top" 
                  Background="White" MinHeight="200" Margin="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="425" />
                </Grid.ColumnDefinitions>

                <TextBlock Text="Wells:" Margin="10" Foreground="Black" TextWrapping="Wrap" 
                           FontWeight="Bold" FontSize="10"/>

                <ListView x:Name="wellsGrid" Grid.Row="1" Grid.Column="0" Margin="8,0,8,8" BorderBrush="Black" BorderThickness="1" 
                          SelectionMode="Single" SelectionChanged="WellsGrid_SelectionChanged">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock TextAlignment="Center" Text="{Binding Attributes[OBJECTID]}" Width="60" />
                            </StackPanel>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

                <TextBlock Grid.Column="1" Margin="10" TextWrapping="Wrap" Foreground="Black"
                           Text="Tops related to the selected well:" FontSize="10" FontWeight="Bold" />
                <ListView x:Name="relationshipsGrid" Grid.Row="1" Grid.Column="1" Margin="0,0,8,8">
                    <ListView.View>
                        <GridView>
                            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Attributes[OBJECTID]}" Width="50" />
                            <GridViewColumn Header="API Number" DisplayMemberBinding="{Binding Attributes[API_NUMBER]}" Width="80" />
                            <GridViewColumn Header="Elevation" DisplayMemberBinding="{Binding Attributes[ELEVATION]}" Width="75" />
                            <GridViewColumn Header="Formation" DisplayMemberBinding="{Binding Attributes[FORMATION]}" Width="150" />
                            <GridViewColumn Header="Top" DisplayMemberBinding="{Binding Attributes[TOP]}" Width="40" />
                        </GridView>
                    </ListView.View>
                </ListView>
            </Grid>
        </Border>

        <Border Background="White" BorderBrush="Black" BorderThickness="2" Margin="30" Width="300"
                HorizontalAlignment="Right" VerticalAlignment="Top">
            <TextBlock Text="Click on the map to highlight well points near a location.  Select wells in the tabular panel below to view related records."
                       Margin="30,20" TextWrapping="Wrap" />
        </Border>
    </Grid>
</UserControl>
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Tasks.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace ArcGISRuntime.Samples.Desktop
{
	/// <summary>
	/// This sample demonstrates how to use a relationship query to display information from a related table for selected features. Clicking on the map highlight a set of wells near the clicked point. Select a well from the list to display related features (tops). The object id of the well is used in the relationship query to return 0 to many related records displayed in the list view. Note that the code requires a relationshipId. Feature layers can have more than one relationship and each relationship is identified by a unique identifier. You can use the Services Directory to find the relationship id.
	/// </summary>
	/// <title>Query Related Tables</title>
	/// <category>Tasks</category>
	/// <subcategory>Query</subcategory>
	public partial class QueryRelatedTables : UserControl
	{
		private GraphicsOverlay _wellsOverlay;
	 
		/// <summary>Construct Spatial Query sample control</summary>
		public QueryRelatedTables()
		{
			InitializeComponent();

			_wellsOverlay = MyMapView.GraphicsOverlays["wellsOverlay"];               
		}

		// Select a set of wells near the click point
		private async void MyMapView_MapViewTapped(object sender, MapViewInputEventArgs e)
		{
			try
			{
				_wellsOverlay.Graphics.Clear();
				wellsGrid.ItemsSource = relationshipsGrid.ItemsSource = null;

				QueryTask queryTask =
					new QueryTask(new Uri("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Petroleum/KSPetro/MapServer/0"));
				
				// Get current viewpoints extent from the MapView
				var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
				var viewpointExtent = currentViewpoint.TargetGeometry.Extent;

				Query query = new Query("1=1")
				{
					Geometry = Expand(viewpointExtent, e.Location, 0.01),
					ReturnGeometry = true,
					OutSpatialReference = MyMapView.SpatialReference,
					OutFields = OutFields.All
				};

				var result = await queryTask.ExecuteAsync(query);
				if (result.FeatureSet.Features != null && result.FeatureSet.Features.Count > 0)
				{
					_wellsOverlay.Graphics.AddRange(result.FeatureSet.Features.OfType<Graphic>());
					wellsGrid.ItemsSource = result.FeatureSet.Features;
					resultsPanel.Visibility = Visibility.Visible;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Query Related Tables");
			}
		}

		// Query for rows related to the selected well in the wells list view
		private async void WellsGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			try
			{
				if (e.AddedItems != null && e.AddedItems.Count > 0)
				{
					QueryTask queryTask =
					   new QueryTask(new Uri("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Petroleum/KSPetro/MapServer/0"));

					//Relationship query
					var objectIds = e.AddedItems.OfType<Graphic>()
						.Select(g => Convert.ToInt64(g.Attributes["OBJECTID"]));

					RelationshipParameters parameters = new RelationshipParameters(new List<long>(objectIds), 3)
					{
						OutSpatialReference = MyMapView.SpatialReference
					};

					parameters.OutFields.AddRange(new string[] { "OBJECTID, API_NUMBER, ELEVATION, FORMATION, TOP" });

					var result = await queryTask.ExecuteRelationshipQueryAsync(parameters);
					relationshipsGrid.ItemsSource = result.RelatedRecordGroups.FirstOrDefault().Value;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Query Related Tables");
			}
		}

		private Envelope Expand(Envelope mapExtent, MapPoint point, double pct)
		{
			return new Envelope(
					point.X - mapExtent.Width * (pct / 2), point.Y - mapExtent.Height * (pct / 2),
					point.X + mapExtent.Width * (pct / 2), point.Y + mapExtent.Height * (pct / 2),
					mapExtent.SpatialReference);
		}
	}
}
Feedback on this topic?