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?

1 Answer 1

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>()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.