Relationships are defined as attributes on properties. This allows Ninja Database Pro to save child and parent items into separate tables. This is useful because the child and parent objects can be queried separately. Each child or parent object must have a primary key. It is also possible to save child or parent objects within the same object. See Object Mode vs Relational Mode. Ninja Database Pro supports Parent and Child relationships. Using these two relationship types it is possible to define all the normal relationships such as one to one, one to many, many to one, and many to many. Here is an example set of classes below on how to define relationships and foreign keys.
public class Order
{
//Primary Key
public long OrderId { get; set; }
//Many to One Relationship
[ForeignKey(Relationship.Parent)]
public Person Buyer { get; set; }
//One to Many Relationship
[ForeignKey(Relationship.Child)]
public List<OrderDetail> OrderDetails { get; set; }
public decimal TotalAmount
{
get { return OrderDetails.Sum(o => o.LineItemCost); }
}
public string Notes { get; set; }
}
public class OrderDetail
{
//Primary Key
public long OrderDetailId { get; set; }
//Foreign Key
[ForeignKey(Relationship.Parent)]
public Order Order { get; set; }
//Foreign Key
[ForeignKey(Relationship.Parent)]
public Product Item { get; set; }
//Normal Property
public int Quantity { get; set; }
//Calculated property
public decimal LineItemCost
{
get
{
return Item.Cost * Quantity;
}
}
}
public class Person
{
public long PersonId { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
}
public class Product
{
public long ProductId { get; set; }
public string Name { get; set; }
public decimal Cost { get; set; }
public byte[] ImageBytes { get; set; }
}