How to reference by id and discriminator in Entity Frameworkbe

I would like to refer to Contacts of different types to one reference object. I have an EF framework that I would like to extend.

public class Contact {}
public class Customer : Contact {}
public class Salesperson : Contact {}
public class Producer : Contact {}
public class ContactPerson : Contact {}

      

It codes the code first, and the database contains the following tables: customers, vendors, manufacturers, and contact groups (no contact table).

Now I want to create links between these objects. For example. Parental relationship between two clients or setting up a contact person for a Client or Producer. And I want to use one relationship class for these different relationships.

My idea was to create a ContactRelation like this:

public enum RelationRole : short {
   Child,
   ContactPerson,
   Head
}

public class ContactRelation {
   Guid ParentId { get; set; }
   string ParentType { get; set; }
   Guid ChildId { get; set; }
   string ChildType { get; set; }
   RelationRole Role { get; set; }
}

      

But I would like the relationship to actually reference Contacts, so I can handle it easily. Is there a way to teach EF this kind of link? I need something like this (in each ContactType)

public class Customer : Contact {
   [ForeignKey("ParentId")]
   //PSEUDO CODE! How to achieve something like this???
   [Discriminator("ParentType", "Customer")] 
   public ICollection<ContactRelations> Children { get; set; }
   [ForeignKey("ChildId")]
   //PSEUDO CODE! How to achieve something like this???
   [Discriminator("ChildType", "Customer")] 
   public ICollection<ContactRelations> Children { get; set; }
}

      

How can I teach this to EF and make it set the type correctly when adding ContactRelations to the collection?

EDIT maybe the last part should be better part of the base class.

+3


source to share





All Articles