1

I have code first implementation for flowing hierarchy,

 BaseContact{
   Public int Id{get;set;}
   public string Name{get;set;} 
//..
 }

 Person:BaseContact{

   public string Designation{get;set;} 
//..
 }
Company:BaseContact{
     public int NumOfEmployees{get;set;} 
//..
 }

I want to identify person or company with by using only the Id value? Currently I am using reflection to identify whether it is a person or company. Is there any other way to identify it without doing too much?

2
  • What do you want to identify person or company with, by using only the Id value? Commented Sep 19, 2011 at 8:53
  • Because in MVC layer depending on the type of the object I want to implement several presentation strategies . Commented Sep 19, 2011 at 9:36

2 Answers 2

6

Without seeing how you initialised your classes I'm going to assume you have a table per concrete type approach.

You can't do it just from the ID, as you don't know which table the ID belongs to. ID 2 in "Person" table is a different entity to ID 3 in "Company". The only practical way to identify only from an ID is using a Table per Hierarchy approach and inspecting the type descriptor.

Some good references http://weblogs.asp.net/manavi/archive/2011/01/03/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines.aspx

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

You can also use a simple is statement instead of reflection. Ie if (entity is Company)

Sign up to request clarification or add additional context in comments.

Comments

4

In your BaseContact (assume it is an abstract class) add abstract property which will be implemented by other two classes.Use Enum to identify the property type as follows.

 public enum MyType
    {
     Person, 
     Company,
    };

    public abstract class BaseContact{
       public abstract MyType ContactType{get;}   
     }

    public class Person:BaseContact
   {

    public override MyType ContactType
    {
      get
      {
        return MyType.Person;
      }      
    }
   }

public class Company:BaseContact
{
    public override MyType ContactType
    {
      get
       {
         return MyType.Company;
       }  
    } 
 }

Use your BaseContact repository to retrieve entities and use enum for type separation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.