Jakobbbb
Jakobbbb

Reputation: 545

EF relationships when adding to database

I have a question about relationships in Entity Framework when adding to database.

I have the following layers

Lets say i have these entities

These entities reference each other. In my service layer I get the course entity and the department entity. Then I do something like:

    Course.Department = department;
    Unitofwork.CourseSet.Add(Course);
    Unitofwork.SaveChanges();

My question is then: Do I also need to add the department entity to the context?

Because even if I dont add the department to the DepartmentSet it is still beeing added to the database. Is there some kind og rule about when to add to the context and when its not necesary

Hope someone can help

Upvotes: 1

Views: 37

Answers (1)

haim770
haim770

Reputation: 49095

You don't need to add related entities separately since EF is able to detect that automatically.

Also, even if you do add it separately, it will have no effect since the related entity is (internally) already attached to the Context and its state is already set to 'Added'.

The 'rule' you're looking for is very simple: if it's not part of the 'root' entity, you'll have to add it separately.

P.S: This is all true for Insert/Add scenario. Update/Edit scenario (from detached entity) is more complicated and changes to related entities usually aren't detected.

Upvotes: 2

Related Questions