I\'m migrating from Linq-to-SQL to Entity Framework (4.4), using Database First with a DbContext. I\'m wondering whether the following behavior is normal:
us
No. Entity framework does this for you. Read Relationships and Navigation Properties for more information.
By assigning a new object to a navigation property. The following code creates a relationship between a course and a
department
. If the objects are attached to the context, thecourse
is also added to thedepartment.Courses
collection, and the corresponding foreign key property on the course object is set to the key property value of thedepartment
.
course.Department = department;
But as you observed, this only happens after you call SaveChanges
or one of the other actions mentioned in the "Synchronizing the changes between the FKs and Navigation properties" portion of the document linked above.
If you are using POCO entities without proxies, you must make sure that the DetectChanges method is called to synchronize the related objects in the context. Note, that the following APIs automatically trigger a DetectChanges call.
- DbSet.Add
- DbSet.Find
- DbSet.Remove
- DbSet.Local
- DbContext.SaveChanges
- DbSet.Attach
- DbContext.GetValidationErrors
- DbContext.Entry
- DbChangeTracker.Entries
- Executing a LINQ query against a DbSet
If this is not happening at all, my guess is that you haven't properly defined StoreID
as the foreign key of the navigation property Store
.