mortenbock
mortenbock

Reputation: 671

Mapping a private property as complex type in Entity Framework

Given this class:

public class Basket
{
    public int Id { get; set; }
    private string SomeProperty { get; set; }
    private Address Address { get; set; }

    public class BasketMapper : EntityTypeConfiguration<Basket>
    {
        public BasketMapper()
        {
            //ValueType property is simple
            Property(b => b.SomeProperty);

            //Complex type needs all properties mapped
            Property(b => b.Address.Street);
            Property(b => b.Address.City);
            Property(b => b.Address.CountryCode);
        }
    }

}

I want my Address property to stay private, but I cannot use the Property(b=>b.Address) because classes are not supported.

Is there a simple way to tell EF to map my Address property as a complex type, the same way it would if it were a public property?

What I want to avoid is having to add all the properties of the Address to my BasketMapper.

Upvotes: 1

Views: 346

Answers (1)

mortenbock
mortenbock

Reputation: 671

Ok, after some trial and error it turns out that EF is not actually considering weather or not my complex type property is private. It just need to know that the type exists, so as Gert Arnold wrote in a comment, doing modelBuilder.ComplexType<Address>() will actually cause EF to read/write all Address properties to the database, even if they are private.

I also found that Property(b => b.Address.Street); will do exactly the same. It will register the entire Address type, not just the Street part, and it will register it for alle properties. So even if I have both a Billing and Shipping address on my basket, both of them would get picked up by EF.

Upvotes: 1

Related Questions