The following sample codes can be used for Web API OData V3 & V4 with a little bit function name changing.
Define Referential Constraint Using Attribute
There is an attribute named “ForeignKeyAttribute” which can be place on:
1.the foreign key property and specify the associated navigation property name, for example:
2.a navigation property and specify the associated foreign key name, for example:
Where, Customer has two keys.
Now, you can build the Edm Model by convention model builder as:
Define Referential Constraint Using Convention
If user doesn’t add any referential constraint, Web API will try to help user to discovery the foreign key automatically. There are two conventions as follows:
1.With same property type and same type name plus key name. For example:
Where, Customer type name “Customer” plus key name “Id” equals the property “CustomerId” in the Order.
2.With same property type and same property name. For example:
Where, Property (key) “CustomerId” in the Customer equals the property “CustomerId” in the Order.
Now, you can build the Edm Model using convention model builder same as above section.
Define Referential Constraint Programmatically
You can call the new added Public APIs (HasRequired, HasOptional) to define the referential constraint when defining a navigation property. For example:
It also supports to define multiple referential constraints, for example:
Define Nullable Referential Constraint Using Convention
Currently, it doesn’t suppport to define nullable referential constraint from attribute and convention method. However, you can do it by Programmatically by calling HasOptional() method:
Then you can get the following result:
Where, CategoryId is nullable while navigation property Supplier is nullable too.