How to access child tables using Entity Framework

I have the following tables: Animaland ConcreteAnimal. I use the first database approach if in this example it makes any difference. Suppose they are separate objects. Then I have 2 DBSet(s)generated and can be separately updated either from the table. Things change when I set ConcreteAnimalas a child Animalin an entity constructor. The Entity Set field ConcreteAnimalin the object designer becomes disabled and is automatically populated with the value of the set of objects of its parent class Animal. DBSetfor is ConcreteAnimalno longer generated in context. This means that I can no longer access the second, child table. How can I add ConcreteAnimalto the database? Is behavior expected? If so, what is its logic?

EDIT: Ok, I tried the following code and it works.

using(var context = new MyEntities())
{
    var concreteAnimal = new ConcreteAnimal
        {
            //setting properties here
            //both for Animal and specific to ConcreteAnimal
        };
    context.Animals.Add(concreteAnimal);
    context.SaveChanges();
}

The magic happened, and both tables were filled with the correct data. It's good. However, this just does not look logical to me, why do we DBSetonly have a base class?

+4
source share
1 answer

You are currently using TPT inheritance.

General information is stored in the Animal table and specific information from the type in their own table.

You will find the information you look at in these articles:

Edit

Why we only have a DBSet for the base class

, , , , , .

TPT , DbSet ( DbSet), , DbSet , .

, ( ), .

public DbSet<ConcreteAnimal> ConcreteAnimals { get; set; }
+2

Source: https://habr.com/ru/post/1627845/


All Articles