How to: Create Associations
This article is relevant to entity models that utilize the deprecated Visual Studio integration of Telerik Data Access. The current documentation of the Data Access framework is available here.
This topic demonstrates how to create a new one-to-many association between the Product and Category entities.
To define an one-to-many association, you have to define both of the navigation ends by using the HasAssociation and WithOpposite methods. The WithOpposite method specifies the inverse property of the relation. If you want to create a constraint in the model, you can use the HasConstraint method. The HasConstraint method specifies the constraint that defines the relation and its endpoints.
When you define a mapping for a collection property, the HasAssociation property expects the type of the property to be IList<T>. Note that in this example, the Products property in the Category class is of type IList<Product>.
productConfiguration.
HasAssociation( p => p.Category ).
WithOpposite( c => c.Products ).
HasConstraint( ( p, c ) => p.CategoryId == c.Id );
productConfiguration.
HasAssociation(Function(p) p.Category).
WithOpposite(Function(c) c.Products).
HasConstraint(Function(p, c) p.CategoryId = c.Id)
Creating Foreign Key Constraints in the Database
By default, when you map associations and update (create) your database by using the Schema Change API, foreign key constraints won't be created in the database. In order to generate DDL script for creating constraints in the database, you should override the CreateModel method in your FluentMetadataSource class and set the NullForeignKey property to True. For more information, see the Creating ForeignKey Constraints topic.
protected override Telerik.OpenAccess.Metadata.MetadataContainer CreateModel()
{
Telerik.OpenAccess.Metadata.MetadataContainer model = base.CreateModel();
model.DefaultMapping.NullForeignKey = true;
return model;
}
Protected Overrides Function CreateModel() As Telerik.OpenAccess.Metadata.MetadataContainer
Dim model As Telerik.OpenAccess.Metadata.MetadataContainer = MyBase.CreateModel()
model.DefaultMapping.NullForeignKey = True
Return model
End Function
The next topic demonstrates how to expose the Product and Category collections from your context class.