entity-frameworkinheritanceentity-framework-6table-per-type

Add child node to existing parent Entity Framework


Let s say i have two classes

[Table("User")]
public class User 
{
    public string Name { get; set; }

    public string Surname { get; set; }
}

[Table("Manager ")]
public class Manager : User
{
    public int Title {get;set;}
}

and i m using entity framework 6.1.2 and table per type approach for saving entity.

Now i want to add a child (i.e. Manager) but there is a parent(i.e. User) for this child.

so what should i do how do i insert only the child node.


Solution

  • You are mixing some OO principles. A manager is a user. This means that if you add a manager to system, you are effectively also adding a user. You can add a user to the system if it is not a manager. Adding a manager will update both user table and manager table. Adding a user that is not a manager will only add an entry in the user table. So in summary. All users both normal and managers will appear in the users table. But for the users that are also manager , there will also be a record in the manager table. The information that belongs to a manager is spread over 2 tables in the database. In EF because you have used inheritance you are using only a manager instance, but because it is derived from user, you get access to the user properties as well. Relational concepts and OO concepts are not the same, EF does the mapping between these distinct concepts for you, hence the name Object Relational Mapping.