Search code examples
c#ef-code-firstentity-framework-6foreign-key-relationship

Entity framework: changing mapped foreign key from required to nullable


I'm trying to change the specifically mapped foreign keys from required to nullable, but for some reason entity framework migration doesn't register the change. Specifically what I have done is change the following code from

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

to

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

Changing the database field to nullable manually makes entity ignore every result with Test_TestId = null.

Is there something that can be done about this?


Solution

  • Consider Overriding the OnModelCreating method inside your DbContext

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext,Configuration>());
    
        base.OnModelCreating(modelBuilder);
    }