public class Order : Entity
{
// Using private fields, allowed since EF Core 1.1
private DateTime _orderDate;
// Other fields ...
private readonly List _orderItems;
public IReadOnlyCollection OrderItems => _orderItems;
protected Order
() { }
public Order
(
int
buyerId,
int
paymentMethodId, Address address)
{
// Initializations ...
}
public void
AddOrderItem
(
int
productId,
string
productName,
decimal
unitPrice,
decimal
discount,
string
pictureUrl,
int
units =
1
)
{
// Validation logic...
var
orderItem =
new OrderItem
(productId, productName,
unitPrice, discount,
pictureUrl, units);
_orderItems.
Add
(orderItem);
}
}
The
OrderItems
property can only be accessed as read-only using
IReadOnlyCollection . This type is read-only so it is protected against regular external
updates.
EF Core provides a way to map the domain model to the physical database without “contaminating”
the domain model. It is pure .NET POCO code, because the mapping action is implemented in the
persistence layer. In that mapping action, you need to configure the fields-to-database mapping. In
the following example of the
OnModelCreating
method from
OrderingContext
and the
OrderEntityTypeConfiguration
class, the call to
SetPropertyAccessMode
tells EF Core to access the
OrderItems
property through its field.
// At OrderingContext.cs from eShopOnContainers
protected