James
James

Reputation: 233

Code First - Entity Framework - Inherited type not displaying all properties

I have a code first entity Model with 3 objects that create 2 tables/entites:

public class Customer
{
    [Key]
    public int ID { get; set; }

    [Required]
    public DateTime DOB { get; set; }
}

public class ExtendedCustomer : Customer
{
    [Required]
    public int Weight { get; set; }
}

public class PhoneNumber
{
    [Key]
    public int ID { get; set; }

    [Required]
    [MaxLength(100)]
    public string PhoneNumber{ get; set; }

    [Required]
    public Customer Customer { get; set; }
}


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().HasOptional(e => e.AddressList).WithMany();
}

As you can see, the Extended customer inherits from Customer and adds another property.

When it generates the tables, there is just a Customer and PhoneNumber table (no Extended customer), and the extended property is correctly in the Customer table.

So far so good.

(Also you'll notice that the phone number table returns a customer, not an extended customer. That is because the model does not necessarily have an extended customer and does not need to know that level of concreteness)

However, when I navigate through context.Customer.First() the extended property is not there in the customer object.

How do I get it there?

Thanks, James

Upvotes: 0

Views: 919

Answers (2)

Henrique Miranda
Henrique Miranda

Reputation: 1108

Since Address.Customer is of Customer type, it will always return a Customer even if it points to ExtendedCustomer data. If it was saved as an ExtendedCustomer, it's properties are there, you just have to type cast it to access them.

var cust = Context.Addresses.First().Customer.First();
var extCust = cust as ExtendedCustomer;
if (extCust != null)
{
    // It's an ExtendedCustomer, you can access it's properties now. ;)
}

Also, this might have useful information for you: http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx

Upvotes: 0

Sebastian Piu
Sebastian Piu

Reputation: 8008

It is not there because, I assume, context.Customer.First() is returning a Customer type (even if the instance is ExtendedCustomer, the static compiler has no way to ensure that)

Depending on what you need to do you can either add ExtendedCustomers to your context or use context.Customers.OfType<ExtendedCustomer>()

Upvotes: 1

Related Questions