Relate features

You relate a feature in one table to a feature in another table for a variety of reasons, such as to allow your users to view information in one table for features in another. For example, you might want a user to be able to view fire hydrant inspection reports from a reports table and general fire hydrant information from a hydrants table for the same set of fire hydrants.

When you relate features, you're editing them because the relate operation changes the attribute of the destination feature. The relate operation associates the two tables by setting up a keyField attribute in the destination feature based on the corresponding origin feature. The keyField value is the origin table feature's primary key or global ID. In this hydrant example, relating a hydrant and an inspection report adds the keyField value of the hydrant feature in the hydrants table (origin table) to the corresponding (hydrant) field in the report feature in the reports table (destination table).

The tables of the two features you want to relate must be in a table relationship with each other (must be related tables). Table relationships are created using ArcGIS Desktop.

The pattern for editing a feature to relate it to another is the same as for editing a "regular" feature, as described in Edit features, whether the feature is the origin feature in a table relationship or the destination feature. When tables participate in a table relationship like this, you can perform additional editing-oriented operations not described in Edit features but described on this page:

Relate two features

You use the relate method to relate a feature in one table to a feature in a different table as long as the two participating tables have a valid relationship between them. The relate method sets up the foreign key (KeyField) value on the destination feature and can be called on either the origin or destination feature.

Relating features is akin to changing the attributes of feature; it's synchronous and done in memory. A feature once related must be added or updated to the table using AddFeatureAsync(feature) or UpdateFeatureAsync(feature) for changes to be committed.

It's important to know the cardinality of the table relationship when you relate features.

The sample feature service at http://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/FeatureServer contains a layer of point features that represent customer requests for service. A related table contains zero or more comments for each feature in the service request layer. The following code uses this service to show how to add a new related comment to a service request feature clicked in the map.

// Identify a feature in the 'service request' layer (from a tap on the map, for example)
IdentifyLayerResult idResult = await MyMapView.IdentifyLayerAsync(serviceRequestLayer, e.Position, 5, false);
ArcGISFeature serviceRequestFeature = idResult.GeoElements.FirstOrDefault() as ArcGISFeature;
if (serviceRequestFeature == null) { return; }


// Get the feature table from the feature
ArcGISFeatureTable serviceRequestTable = serviceRequestFeature.FeatureTable as ArcGISFeatureTable;


// Get a list of tables related to the 'service requests' feature table
IReadOnlyList<ArcGISFeatureTable> relatedTables = serviceRequestTable.GetRelatedTables();


// Assume the comments table is the first (only?) related table
// (if there are many related tables, you can loop through the collection and check the table name)
ArcGISFeatureTable commentsTable = relatedTables.FirstOrDefault();


// Create a new feature in the comments table
ArcGISFeature newComment = commentsTable.CreateFeature() as ArcGISFeature;


// Add comment text to the 'comments' attribute
newComment.Attributes["comments"] = "Please show up on time!";


// Relate the selected service request to the new comment
serviceRequestFeature.RelateFeature(newComment);

Unrelate features

You may want to unrelate two already related features. For example, when a feature has a constraint violation, such as an invalid cardinality, you may want to undo the last relate operation that caused the violation. Unrelating features resets the key field of the destination feature. Like the relate method, unrelate is also synchronous and is done in memory. Therefore AddFeatureAsync(feature) or UpdateFeatureAsync(feature) must be called for changes to be committed to the table.

The following code loops through related comments for a service request feature and removes those more than seven days old.

// Get the layer info from the service request table
ArcGISFeatureLayerInfo serviceRequestLayerInfo = serviceRequestTable.LayerInfo;


// Get all relationship infos
IReadOnlyList<RelationshipInfo> relationships = serviceRequestLayerInfo.RelationshipInfos;


// Find the info for the 'service request comments' relationship
var relatedCommentsInfo = (from r in relationships
                           where r.Name == "ss6_gdb_ServiceRequestComment"
                           select r).FirstOrDefault();


// Create a relationship query parameters using this relationship info
RelatedQueryParameters relatedCommentsQueryParams = new RelatedQueryParameters(relatedCommentsInfo);


// Query the service requests table to get related comments
IReadOnlyList<RelatedFeatureQueryResult> relateResults = await serviceRequestTable.QueryRelatedFeaturesAsync(serviceRequestFeature, relatedCommentsQueryParams);
if (relateResults.Count > 0)
{
    // Get the comments from the relationship results
    var relatedComments = relateResults.FirstOrDefault().ToArray();


    // Loop through all comments related to this service request
    foreach (ArcGISFeature relatedFeature in relatedComments)
    {
        // Load the related feature before accessing attribute values
        await relatedFeature.LoadAsync();


        // Get the date and time this comment was submitted
        DateTimeOffset submittedOn = (DateTimeOffset)relatedFeature.Attributes["submitdt"];


        // See if the comment is more than seven days old
        if (DateTime.Now.AddDays(-7) > submittedOn)
        {
            // Unrelate the comment from the service request (doesn't delete the related feature)
            serviceRequestFeature.UnrelateFeature(relatedFeature);
        }
    }


    // Update the feature to commit changes to the table
    await serviceRequestTable.UpdateFeatureAsync(serviceRequestFeature);
}

Validate the relationship constraints of a feature

You can check if a given feature violates any relationship constraints (for example, when a hydrant inspection report, is being added by a user), such as cardinality violations. In 1:1 relationships, if an origin feature is already related to a destination feature, no other destination feature can be related to it. In 1:n relationships, a destination feature can be related to only one origin feature (while the other way around is permitted). For more info on cardinality and types of relationships, see Relationship class properties in the ArcGIS Desktop help.

The following branching statement checks for a relationship constraint violation for the service request feature and its related comment records.

// See if this service request feature violates relationship constraints with comments
RelationshipConstraintViolationType constraintViolation = await commentsTable.ValidateRelationshipConstraintsAsync(serviceRequestFeature);


// Check for a constraint violations
if (constraintViolation == RelationshipConstraintViolationType.Cardinality)
{
    // Cardinality means the wrong number of related features (more than 1 related record in a 1:1 relationship, for example)
}
else if (constraintViolation == RelationshipConstraintViolationType.Orphaned)
{
    // Orphaned means a record with no related feature when one is required
}
else
{
    // No violations
}

Note that an update operation on a feature succeeds even if a relationship constraint has been violated by the edit. This is consistent handling with ArcGIS Server and ArcGIS Desktop, which do not enforce cardinality violations. ArcGIS Desktop provides a Validate Feature tool, which allows you to recover from violations in a back office operation after applying edits or syncing, if you choose to do so. See Validating features and relationships in ArcMap for more information. However, if you wish to check for violations in your app and recover from them, you can use the validate method.

Another type of constraint violation captured by the validatie method occurs in a composite relationship when an orphan feature is added to the destination table without relating it to an origin feature. You can recover from this violation by relating the orphaned destination feature to a valid origin feature.

Tip:

Performance tip: If the related features are not local to the device, the validate method makes network calls to query for them. As a result, it can negatively impact performance when used on a number of features. This hit to performance is why edit operations such as add, update, and delete do not proactively check for relationship constraint violations.

Additional information

Getting related tables for a layer or table on the map returns only those tables on the map. Similarly related queries require both origin and destination table/layer to be present on the map. For tables not on the map, you can query them using regular query operations but cannot use related queries. You can also view what relationships the tables participate in.

All the tables participating in a relationship must be present in the data source. ArcGIS Runtime supports related tables in the following data sources:

  • ArcGIS feature service
  • ArcGIS map service
  • Geodatabase downloaded from a feature service
  • Geodatabase in a mobile map package

Two participating tables can have one of the following cardinalities: one-to-one, one-to-many, or many-to-many.

When defining relationships, one table must be origin and the other destination. A table can participate in more than one relationship. A table can play a destination role in one relationship and origin in another, resulting in nested relationships.

Simple and composite workflow-based relationships are supported:

  • In a simple relationship, features in the destination table are independent to features in the origin table. For example, a transformer and an electric pole may be related but they can also exist their own. Deleting an origin feature resets the keyField of the relationship to NULL in the destination feature.
  • In a composite relationship, each feature in the destination table is expected to be related to an origin feature. In other words, any orphan destination features are considered a violation of the relationship. For example, a building and its mailbox must be related. While the building (origin) can exist on its own, a mailbox (destination) must be related to a building. When an origin feature is deleted, the destination feature should also be deleted. This is known as a cascade delete.