w0051977
w0051977

Reputation: 15787

Mapping multiple classes to a single entity

I recently read this article again: http://enterprisecraftsmanship.com/2015/04/20/types-of-cqrs/ Please see the code below from type 1:

public class CustomerRepository
{
    public void Save(Customer customer) { /* … */ }
    public Customer GetById(int id) { /* … */ }
    public IReadOnlyList<CustomerDto> Search(string name) { /* … */ }
}

Notice that there are two separate objects for Customers i.e. Customer and CustomerDto. I believe entity framework only allows you to map one entity to one class. How does it cater for the code above?

Upvotes: 2

Views: 767

Answers (1)

Jasen
Jasen

Reputation: 14250

The DTO classes are not saved to the database. The properties are mapped to the entities.

var query = db.Customer.First(c => c.id == id);
var customerDto = Map<CustomerDto>(query);

The repository exposes DTO classes to its clients. The implementation details uses entities. This isolates EF within the data layer.

The DTO properties might not even be a 1:1 mapping to an entity -- there could be many entity classes involved yet a relatively flat DTO.

public class CustomerInfoDto
{
    public int CustomerId { get; set; }
    // ... some customer properties
    public int CustomerExtendedId { get; set; }
    // ... some additional properties
}

var info =  from c in db.Customers
            join e in db.CustomerExtended on c.Id equals e.CustomerId
            select new CustomerInfoDto
            {
                CustomerId = c.Id,
                Name = c.Name,
                CustomerExtendedId = e.Id,
                LastAccess = e.LastAccess
            };

Upvotes: 1

Related Questions