Data Access has been discontinued. Please refer to this page for more information.

Creating ForeignKey Constraints

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. The following code-snippet is from the Overview. Note that first you should use the WithOpposite method and after that create a constraint via the HasConstraint method. The WithOpposite method specifies the inverse property of the relation. The HasConstraint method specifies the constraint that defines the relation and its endpoints. In this example the child entity is the Product and the CategoryId is the foreign key. The Category entity is the parent.

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)

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. The NullForeignKey property controls whether foreign keys can be null. By default, constraints are not created in the database for the associations defined by Fluent Mapping API. Only overriding the CreateModel method and setting this property to True will enable this functionality.

protected override MetadataContainer CreateModel()
   MetadataContainer container = base.CreateModel();
   container.DefaultMapping.NullForeignKey = true;
   return container;
Protected Overrides Function CreateModel() As MetadataContainer
 Dim container As MetadataContainer = MyBase.CreateModel()
 container.DefaultMapping.NullForeignKey = True
 Return container
End Function