Do I have to set foreign key properties manually when I change associations?

后端 未结 1 674
春和景丽
春和景丽 2020-12-31 15:56

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         


        
相关标签:
1条回答
  • 2020-12-31 16:20

    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, the course is also added to the department.Courses collection, and the corresponding foreign key property on the course object is set to the key property value of the department.

    • 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.

    0 讨论(0)
提交回复
热议问题