1

I am learning EF and Model First approach. I have a table, which has inheritance.

Here it is my EDM scheme: http://gyazo.com/fbec21b5fbfc47dd76ff3eaa38f86d36.png

I am not sure about my queries, INSERT, UPDATE and DELETE. Am i right?

    private static void AddNewEmployee()
    {
        using (EmployeesModelContainer context = new EmployeesModelContainer())
        {
            Employee newEmployee = new Employee
            {
                Name = "Вася",
                Surname = "Пупкин",
                Age = 34,
                Sex = Sex.Man,
                ProfessionId = 4,
                EducationLevelId = 1
            };

            context.Persons.Add(newEmployee);

            context.SaveChanges();
        }
    }

    private static void UpdateEmployee()
    {
        using (EmployeesModelContainer context = new EmployeesModelContainer())
        {
            var updateEmployeeQuery = (from employee in context.Persons.OfType<Employee>()
                                       where employee.Name == "Вася"
                                       select employee).FirstOrDefault();

            updateEmployeeQuery.Age = 39;
            updateEmployeeQuery.EducationLevelId = 2;

            context.SaveChanges();
        }
    }

    private static void DeleteEmployee()
    {
        using (EmployeesModelContainer context = new EmployeesModelContainer())
        {
            var deleteEmployeeQuery = (from employee in context.Persons.OfType<Employee>()
                                       where employee.Name == "Вася"
                                       select employee).FirstOrDefault();

            context.Persons.Remove(deleteEmployeeQuery);

            context.SaveChanges();
        }
    }

The question is, If I need to add or delete some data in Employees table, why i am adding or deleting in Person table and it is allright? Data adding in Person and in Employees tables. And if I Updating some data in Employees table, why the data is updating in Person table correctly?

Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158
BJladu4
  • 263
  • 4
  • 15

1 Answers1

1

You are correct. You can add an Employee to the Persons table, both the Employee table and Persons table will be inserted into. Likewise, adding a Person to the Person table does not touch the Employee table.

To query, you use context.Persons.OfType<Employee>()

Sam Leach
  • 12,746
  • 9
  • 45
  • 73