How to store collection of value object in single field without creating new table in EF Core

Viewed 516

I am using EF Core as my ORM, and I am learning Domain Driven Design.

As you may already know in DDD value object have no identifier and creating a separate table for value objects is not good practice.

But I want store a collection of value object without creating a new table, so how should I do that? Look at below example:

public class User : Entity 
{
      public ICollection<Address> Addresses { get; set; }
}

public class Address : ValueObject 
{
     public string Country { get; set; }
     public string City { get; set; }
     // some other properties
}
1 Answers

so as alexander said , i decide to use value conversions(like below) :

public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.Property(user => user.Addresses)
            .HasConversion(
            a => (string)JsonConvert.SerializeObject(a),
            a => JsonConvert.DeserializeObject<List<Address>>(a));
        /*builder.HasData(Data.GetData<User>());*/
    }
}

and now a collection of address will store in single field

Related