Naor
Naor

Reputation: 24103

Use derived class instead of abstract type in Entity Framework

I have ThirdParty entity and two derived entities: Supplier and Customer.
I have another entity called Worker, with Supplier as a member:

public abstract class ThirdParty { }
public class Supplier : ThirdParty { }
public class Customer : ThirdParty { }

public class Worker {
    public virtual string Name {get;set;}
    public virtual Supplier Supplier {get;set;}
}

When I get Worker from the database using the entity framework I get the following exception:

There are no EntitySets defined for the specified entity type 'CompanyData.Supplier'. If 'CompanyData.Supplier' is a derived type, use the base type instead.

The error tells me to use ThirdParty type instead of Supplier type for the Supplier member. But I want to Supplier to be with Supplier type and not ThirdParty. How can I fix this?

Upvotes: 2

Views: 2718

Answers (2)

Neil Fenwick
Neil Fenwick

Reputation: 6184

It sounds like you need to add a Table Per Hierarchy (TPH) definition to your Entity Model definition. (Store all data for derived types in one table)

Here are some links that might help you set that up:

Walkthrough: Mapping Inheritance - Table-per-Hierarchy (Entity Data Model Tools)

How to: Define a Model with Table-per-Hierarchy Inheritance

How to choose an Inheritance Strategy

Upvotes: 1

SpeedBirdNine
SpeedBirdNine

Reputation: 4676

Use a reference(variable) of ThirdParty to store members belonging to both Supplier and Customer (abstract classes cannot have instances but can have references). Any virtual methods of ThirdParty will have implementation in both Supplier and Customer, and any methods that have different implementations for ThirdParty, Supplier and Customer, the appropriate method will be called because of Polymorphism. So receiving them from the DB in a reference of ThirdParty will not cause any problem. Ofcourse there'll be small problem if there are methods that are not in ThirdParty but in either Supplier or Customer, but again you can always typcast.

Hope this helps.

Upvotes: 2

Related Questions