EF Code First Abstract Relationship?

I have a class that inherits a base class, to which another class has a relationship.

Example:

  • Base Class: Animal
  • Subclass 1: Dog
  • Subclass 2: Cat
  • One-to-Many Related Table: Vaccination
    • A dog may have several vaccinations. This is implemented as the <Vaccination> list.
    • A cat may have several vaccinations.
    • A vaccination record can only have one animal associated with it.
    • Vaccination does not know whether it is related to a dog or a cat. (Dogs and cats use non-colliding GUIDs.)

No table Animal; Animal is an abstract class. But Vaccination knows only about animals, not about Dog. (EF, however, knows about everything.) I have class libraries so that Animal and Vaccination are in the main library, and Dog is in another library that references the main library.

When using the Entity Framework Code, the Vaccinations table first receives an additional column: Dog_ID, as the list of dog classes <Vaccination> explicit declaration creates output. Thus, this column displays the vaccination record for the dog. That would be good, except for the fact that I want to share this extra column with several types of Animal. So, for example, instead of having Dog_ID and Cat_ID, I would like to have an Animal_ID that could join Dog or Cat.

Since Animal is abstract and does not have a DB table, can I accomplish this, perhaps with a free statement declaration and / or property / attribute?

+4
source share
3 answers

An additional FK column will always be added to the Vaccination table for each vaccinated animal type, unless you create an Animal table and relate to this table. EF cannot display and abstract high-level relationships β€” relationships must follow the same rules as if you were creating them directly in the database.

If only some animals can be vaccinated, you can add another table to the hierarchy and establish a relationship with this new table (EF cannot work with interfaces). You will need a table for each type for this, and this will make the performance of your queries much worse in the current version of EF.

+3
source

Assuming all your animals get vaccinated

 public abstract class Animal { public string ID { get; set; } public ICollection<Vaccination> Vaccinations { get; set; } } public class Vaccination { public string ID { get; set; } public string AnimalID { get; set; } public virtual Animal Animal { get; set; } //other properties } 

Then you can inherit Cat and Dog and use Table per Type mapping.

+2
source

So, when I implemented what is currently marked as an answer (what I ultimately need to do next and create the Animal table), I ran into problems because, as I explained in my question, I have an isolated project, declaring "Dog" ", and for this and related issues I have sent here , here , and here .

+1
source

All Articles