Choosing One table among two tables on the basis of some attribute value in MVC3 and EF

Go To StackoverFlow.com

1

Suppose I have a base class Component and two derived classes ComponentA and ComponentB, something like below:

public class Component
{
   public int ComponentID {get; set;}
   public int ComponentType {get; set;}
   // some other statements ...
}

And then

public class ComponentA : Component
{
   // some statements ...
}

public class ComponentB : Component
{
   // some statements ...
}

Now, on the basis of the value of the COmponentType in class Component, How to switch to ComponentA or ComponentB and retrieve their related data.

This is one of the examples how to do this in edmx, but I want to know is there any way to do the same thing in Code First approach in EF. http://www.c-sharpcorner.com/UploadFile/ff2f08/entity-framework-4-0-tph-part-2/

2012-04-04 04:03
by SKumar


0

You can found TPH (Table per Hierarchy) with code first here

2012-04-04 08:02
by ADIMO


0

You can remove the ComponentType property and EF will automatically create a Component table with a Discriminator column that is used to discriminate (duh) between the subclasses.

If you need a specific column name and/or data type for the discriminator column you can override the defaults in the OnModelCreating event of your DbContext, either directly, or by an EntityTypeConfiguration e.g. by doing

Map(m => m.Requires("ComponentType").HasValue(1);

for each subtype. (HasValue with a different value each time, obviously).

You will create a property DbSet<Component> in the context. This returns all components, irrespective of type. If you only want ComponentAs do

context.Components.OfType<ComponentA>(). ...

Oh, and Component should be an abstract class.

2012-04-05 19:56
by Gert Arnold
Ads