【问题标题】:Entity Framework 5 - Not populating foreign key实体框架 5 - 不填充外键
【发布时间】:2013-06-26 12:03:40
【问题描述】:

我对实体框架非常陌生,所以如果这是一个愚蠢的问题,我深表歉意......

这是我的 POCO:

[Table("RegistrationCodes")]
public class RegistrationCode
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public Guid Code { get; set; }

    public int? UserId { get; set; }

    [ForeignKey("UserId")]
    public UserProfile User { get; set; }

    [StringLength(500)]
    public string Notes { get; set; }
}

当我使用下面的代码从我的 DBSet 中检索对象时,UserId 始终为空。

return this.Context.RegistrationCodes.FirstOrDefault(c => c.Code == code);

我检查了数据库并确认 UserId 不为空。此外,我已经分析并且可以看到正在从数据库中请求 UserId。

任何帮助将不胜感激。

【问题讨论】:

  • 是空的 UserId 还是 UserProfile?
  • UserId 和 UserProfile 都是 null 是 null

标签: entity-framework-5


【解决方案1】:

哦,天哪,我不觉得自己很愚蠢......

这就是发生的事情,我运行代码,我可以看到数据库中的 UserId 字段已更新。每次我重新启动应用程序时,代码迁移都会运行 add 对表执行 AddOrUpdate 操作,这将使 UserId 列清空。

我们可以一起删除这个问题吗?

【讨论】:

  • 在此处留下问题并接受您自己的答案。这是关于始终运行的Seed 方法可能导致的陷阱的一个很好的例子。其他人也遇到过这个问题,比如这里:stackoverflow.com/questions/13510341/…
猜你喜欢
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多