开发者

Entity Framework code first Inheritance Issue

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开发者_C百科 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?


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜