【问题标题】:Entity framework: changing mapped foreign key from required to nullable实体框架:将映射外键从必需更改为可为空
【发布时间】:2014-12-22 11:59:52
【问题描述】:

我正在尝试将特定映射的外键从必需更改为可为空,但由于某种原因,实体框架迁移未注册更改。具体来说,我所做的是从

更改以下代码
public int Test_TestId { get; set; }
[ForeignKey("Test_TestId")]
public Test Test { get; set; }

public int? Test_TestId { get; set; }
[ForeignKey("Test_TestId")]
public Test Test { get; set; }

手动将数据库字段更改为可为 null 会使实体忽略 Test_TestId = null 的每个结果。

对此有什么可以做的吗?

【问题讨论】:

  • 你是先用代码吗?
  • 欢迎来到 StackOverflow!请参阅"Should questions include “tags” in their titles?",其中的共识是“不,他们不应该”!
  • 您的迁移是否会影响其他更改。我已经多次进行这种确切的更改,并且迁移过程从未失败过。

标签: c# ef-code-first entity-framework-6 foreign-key-relationship


【解决方案1】:

考虑在 DbContext 中覆盖 OnModelCreating 方法

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext,Configuration>());

    base.OnModelCreating(modelBuilder);
}

【讨论】:

    猜你喜欢
    • 2015-04-27
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多