gpt4 book ai didi

entity-framework - 更改关联时是否必须手动设置外键属性?

转载 作者:行者123 更新时间:2023-12-04 04:18:01 26 4
gpt4 key购买 nike

我正在使用数据库优先和DbContext从Linq-to-SQL迁移到Entity Framework(4.4)。我想知道以下行为是否正常:

using (var e = new AgendaEntities()) {
var store = e.Stores.First();
var office = e.Offices.Create();
office.Store = store; // Set association
Console.WriteLine(office.StoreID); // shows Guid.Empty, expected store.ID!
}

在L2S中,将 Store关联设置为实体也会更新 StoreID key 。在EF中,这似乎没有发生。这与实体是新实体还是从上下文加载无关。

当我 SaveChanges时,它可以正确保存并更新 StoreID以匹配 office.ID,但是为什么仅在保存后才发生呢?

有什么我想念的东西吗?还是现在应该手动使外键保持同步?

解决方案编辑:
这称为属性修复,过去通常由生成的代理自动完成。但是,使用 DbContext不再是这种情况。根据 this Connect issue,这是设计使然。

Hello, The DbContext template actually doesn't generate classes that will be used as change tracking proxies - just lazy loading proxies (which don't do fix-up). We made this decision because change tracking proxies are complex and have a lot of nuances that can be very confusing to developers. If you want fix-up to occur before SaveChanges you can call myContext.ChangeTracker.DetectChanges. ~EF Team



另一种方法是调用 DbContext.Entry(entity),它将同步实体。在本文中对此进行了描述: Relationships and Navigation Properties,“同步FK和导航属性之间的更改”

最佳答案

否。 Entity Framework 可为您完成此任务。阅读Relationships and Navigation Properties以获取更多信息。

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;


但是,正如您观察到的那样,只有在调用 SaveChanges或上面链接的文档的“同步FK和导航属性之间的更改”部分中提到的其他操作之一之后,才会发生这种情况。

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


如果这根本没有发生,我想您还没有正确地将 StoreID定义为导航属性 Store的外键。

关于entity-framework - 更改关联时是否必须手动设置外键属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15553688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com