I have designed domain models
using classes
and they are the ones that get passed around.
The API Request/Response model
doesn't leave controller boundary, i.e. they get mapped to/from domain models either in controller or using mapper.
In general, the argument against using struct
is to avoid large models, and avoid passing them around, apart from the general value type traits. With first two no longer being a concern, should I start using structs given that they might be better choice for short lived objects.
Example, API model,
//Domain Model
public class Order : Entity
{
public DateTime Date { get; }
public Customer Customer { get; }
public IList<OrderItem> Items { get; }
public Order(int id, DateTime date, Customer customer, IList<OrderItem> items)
{
Id = id;
Date = date;
Customer = customer;
Items = items;
}
}
//API Model
public class OrderDto //or struct
{
public int Id { get; set; }
public DateTime Date { get; set; }
public string CustomerName { get; set; }
public decimal TotalAmount { get; set; }
public static OrderDto FromDomain(Order order)
{
return new OrderDto
{
Id = order.Id,
Date = order.Date,
CustomerName = order.CustomerName,
TotalAmount = order.TotalAmount
};
}
public Order ToDomain()
{
return new Order(Id, Date, CustomerName, TotalAmount);
}
}
public class OrderController:ControllerBase
{
[HttpPost]
public void CreateOrder(Order order)
{
_service.AddOrder(order.ToDomainModel);
}
}