Entity Framework 6迁移时生成TempId3列的原因及用途疑问
EF Core自动生成TempId3列的原因解析
问题场景
实体类定义
public abstract class DocumentBaseModel { public int Id { get; set; } } public class SaleCompileDocument : DocumentBaseModel { public ICollection<EmailNotification> EmailNotifications { get; set; } } public class EmailNotification { public Guid Id { get; set; } public int? DocumentId { get; set; } public SaleCompileDocument Document { get; set; } }
DbContext关系配置
modelBuilder.Entity<EmailNotification>() .HasOne(x => x.Document) .WithMany(x => x.EmailNotifications) .HasForeignKey(x => x.DocumentId) .HasPrincipalKey(z => z.Id);
迁移异常结果
执行迁移后,SaleCompileDocuments表被自动添加了无业务意义的列:
migrationBuilder.AddColumn<int>( name: "TempId3", schema: "api", table: "SaleCompileDocuments", type: "integer", nullable: false, defaultValue: 0);
而移除EmailNotification中的Document导航属性,改为单向导航配置后,迁移不再生成该列:
// 修改后的EmailNotification类 public class EmailNotification { public int? SaleDocumentId { get; set; } //public SaleCompileDocument SaleCompileDocument { get; set; } } // 修改后的DbContext配置 modelBuilder.Entity<SaleCompileDocument>() .HasMany(x => x.EmailNotifications) .WithOne() .HasForeignKey(x => x.SaleDocumentId);
问题解答
1. TempId3是什么?
TempId3是EF Core自动生成的临时影子属性,名字里的数字是序号(避免重名)。这类属性不会出现在你的实体类代码中,仅存在于EF Core的模型元数据里,最终被同步到数据库表结构中。
2. 为什么会生成它?
核心原因是EF Core在双向导航关系的解析中出现了主键识别混淆:
SaleCompileDocument继承自含Id属性的抽象基类,EF Core默认已将基类Id作为派生类的主键,但双向导航(EmailNotification.Document和SaleCompileDocument.EmailNotifications)的存在,加上显式配置HasPrincipalKey的操作,导致EF Core内部错误判断当前的主键-外键映射不完整,自动生成影子属性来“补全”它认为缺失的关联关系。- 改为单向导航后,EF Core能清晰识别
SaleDocumentId作为外键关联SaleCompileDocument的主键Id,不会再触发错误的影子属性生成。
3. 它的作用是什么?
这个列没有任何业务作用,属于EF Core关系解析错误后的冗余产物,只会造成数据库表结构的不必要膨胀,完全应该通过修正关系配置来避免生成。
内容的提问来源于stack exchange,提问作者dm k
相关产品推荐
相关产品推荐

