4

I have the following classes:

public class Customer
{
    public int CustomerId { get; private set; }
    public string Name { get; private set; }
    public Address MailingAddress { get; private set; }
    public Address BillingAddress { get; private set; }
    public Address InvoiceAddress { get; private set; }
}

public class Address //this is a Value Object, with no Id
{
    public int CityID { get; private set; }
    public string Address { get; private set; }
    public string ZipCode { get; private set; }

    public virtual City City { get; private set; }
}

public class City
{
    public int CityID { get; private set; }
    public string Name { get; private set; }
}

Assuming that Value Objects in Domain-Driven Design have no identity, how can I map the above scenario into different tables, using EF Code-First? Is this approach possible?

I don't really like to have all fields of different addresses on the same customer table, but at the same time, i don't wanna make my domain dirty with identities for Value Objects.

Felipe Romero
  • 179
  • 3
  • 9
GuFigueiredo
  • 635
  • 1
  • 9
  • 18

2 Answers2

3

I agree with you that value objects need different treatment than entity objects. After all, when two persons have the same DOB, we don't store one date object to which these persons refer.

However, in my view a class model that's mapped to a store model is not a domain model. It may get close if you're lucky, but its primary responsibility is to act as a data access layer. And these data happen to be relational since the word of Codd.

Everything you want to store in a relational database must have an identity. Same for your addresses. Since you don't want them to be part of the Customer table (as composite entities) you have no other option than to store them with identities in a separate table. It's not that bad.

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
1

Although it's not a good idea to use relational data base when you are using DDD because of it's redundancy in database, but you can map the value object of DDD in a seperate table by assigning the value object as primary key in table (there is no other choice).

 public class AddressMapping : EntityTypeConfiguration<Address>
    {
        public AddressMapping()
        {
            HasKey(t => t.Address);
            Property(t => t.ZipCode); 
            // balh blah
        }
    }

value object should be immutable, so you should set the property as private set in your model. note: sql server wont let you to persist more that 15000 char in primary key as your primary key is address. so your value object must be short enough not only for sql server limitation on primary keys.

Ehsan
  • 816
  • 9
  • 27