Knight Data Access Layer
Mapping Relationships VB.NET
Basic Tasks VB.NET > Mapping > Mapping Relationships VB.NET

Relationships are automatically mapped as long as the primary keys are integer or long and the default convention is used.  References to a single class are considered parent entities.  A list of classes are considered child objects.  In this way, many to many relationships are automatically handled.  It is possible to have a one to one child relationship.  The default automatic relationship mapping can be overridden with attributes. 

The default mapping for parent objects is to create a foreign key constraint with a No Action clause with an associated index.  Some databases do not allow constraints to be added after a table has already been created.  Foreign key constraints are only added during initial table creation with the Setup command. 

Public Class Order

 

'Primary Key

<ColumnMapping("OrderId", System.Data.DbType.Int32), PrimaryKey(PrimaryKeyType.Identity)>

Public Property OrderId() As Integer

 

'Many to One Relationship

<ParentObject(GetType(Person), "PersonId", ForeignKeyAction.Cascade, ForeignKeyAction.Cascade)>

Public Property Buyer() As Person

 

'One to Many Relationship

<ChildObject("OrderId")>

Public Property OrderDetails() As List(Of OrderDetail)

  

Public ReadOnly Property TotalAmount() As Decimal

Get

 

If OrderDetails Is Nothing Then

Return 0

End If

 

Return OrderDetails.Sum(Function(o) o.LineItemCost)

End Get

End Property

 

 

Public Property Notes() As String

Public Property ShippingCost() As Decimal

Public Property Tax() As Decimal?

End Class

 

Public Class OrderDetail

 

'Primary Key

Public Property OrderDetailId() As Integer

 

'Foreign Key

<ParentObject("OrderId")>

Public Property Order() As Order

 

'Foreign Key

ParentObject(GetType(Product), "ProductId", ForeignKeyAction.Cascade, ForeignKeyAction.Cascade)>

Public Property Item() As Product

 

'Normal Property

Public Property Quantity() As Integer

 

'Calculated property

Public ReadOnly Property LineItemCost() As Decimal

Get

 

Return Item.Cost * Quantity

End Get

End Property

End Class

 

Public Class Product

  

Public Property ProductId() As Integer

Public Property ProductName() As String

Public Property Cost() As Decimal

End Class