Skip to content
Auswöger Matthias edited this page Apr 29, 2021 · 1 revision

Add multiple orders to the customer entity

Objective

In the following tutorial we take the result of Part 2 and improve it. We will add an Orders list reference to our Customer entity and add 2 orders to the customer.

Steps

Order entity

Add a new Order entity class that look like this:

[Table("Order")]
public abstract class Order
{
    [Mapping(FieldName="EntityId"), IsPrimaryKey]
    public abstract int Id { get; }

    [ForeignObjectMapping("Customer")]
    public abstract Customer Customer { get; set; }

    [Mapping(FieldName = "OrderNumber")]
    public abstract string OrderNumber { get; set; }
}

Note that it has a Customer reference. This is required in order to link it to the customer later.

Register entity

Change the setup method to register the Order entity too, as shown here:

RelationalObjectStore relationalObjectStore = 
	new RelationalObjectStore("Data Source=Database.db", DataBaseProvider.Instance)
		.Register<Customer>()
		.Register<Country>()
		.Register<Order>();

Add reference list mapping

Add the Orders reference list property to the Customer entity so that it looks as follows:

[ReferenceListMapping(typeof(Order), nameof(Order.Customer))]
public abstract IEnumerable<Order> Orders { get; }

The first parameter of the ReferenceListMapping sets the type of the items returned by the list. The second one sets the name of the property that is pointing back to the current object. Important here is that it is the name of the property, not the name of the field in the database. The return value of the property is in this case set to IEnumerable<Order>, but it doesn't need to. It can also be returned as ICollection<Order> or IQueryable<Order>.

Create two Orders

Insert the following code lines below the ones that are creating the customer.

Order order = ObjectStoreManager.DefaultObjectStore.CreateObject<Order>();
order.Customer = customer;
order.OrderNumber = "ON01234";

Order order2 = ObjectStoreManager.DefaultObjectStore.CreateObject<Order>();
order2.Customer = customer;
order2.OrderNumber = "ON56789";

This does not just create the orders, but also assign them to the customer.

Save the orders

What do you need to do in order to save the orders too? It's simple, nothing. The already existing line:

ObjectStoreManager.DefaultObjectStore.GetQueryable<Customer>().Save();

saves the customer and also by default all referenced lists. You can change this behavior by setting the SaveCascade property of the ReferenceListMapping attribute.

Full example

Checkout the full example here.