Knight Data Access Layer
Mapping Relationships
Basic Tasks C# > Mapping > Mapping Relationships

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, xml or code. 

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. 

Mapping with Attributes

 

public class Order

{

//Primary Key

[ColumnMapping("OrderId", System.Data.DbType.Int32), PrimaryKey(PrimaryKeyType.Identity)]

public int OrderId { get; set; }

 

//Many to One Relationship

[ParentObject(typeof(Person), "PersonId", ForeignKeyAction.Cascade, ForeignKeyAction.Cascade)]

public Person Buyer { get; set; }

 

//One to Many Relationship

[ChildObject("OrderId")]

public List<OrderDetail> OrderDetails { get; set; }

 

public decimal TotalAmount

{

get

{

if (OrderDetails == null)

return 0;

 

return OrderDetails.Sum(o => o.LineItemCost);

}

}

 

public string Notes { get; set; }

public decimal ShippingCost { get; set; }

public decimal? Tax { get; set; }

}

 

public class OrderDetail

{

//Primary Key

public int OrderDetailId { get; set; }

 

//Foreign Key

[ParentObject("OrderId")]

public Order Order { get; set; }

 

//Foreign Key

[ParentObject(typeof(Product), "ProductId", ForeignKeyAction.Cascade, ForeignKeyAction.Cascade)]

public Product Item { get; set; }

 

//Normal Property

public int Quantity { get; set; }

 

//Calculated property

public decimal LineItemCost

{

get

{

return Item.Cost * Quantity;

}

}

}

 

public class Product

{

public int ProductId { get; set; }

public string ProductName { get; set; }

public decimal Cost { get; set; }

}