0

I'm using code first with migrations to build and keep changes to the db in sync.

If there is a class Person that has a property that points to a class FavoriteColor the db schema that gets created is a Person table with a FK called FavoriteColor_Id which is non-nullable.

I need to have that column allow nulls since Person may or may not have a favorite color.

Thx

1 Answer 1

1

Ok once again with a good nights sleep I came in to work fresh and was able to tackle this in minutes.

Basically what had happened is that I was expecting that I would change my model class and a nice new migration cs file would be generated for me. There was no change to make to the model class since EF had auto generated this FK for me originally. I then realized that I could still run add-migration from the package manager console and it would create a new file for me where I could add my own code. I also needed to understand the difference between the Up() and Down() method. Sometimes you take these things for granted when everything is auto generated for you.

Here is what solved my issue:

public override void Up()
{
    AlterColumn("dbo.Person", "FavoriteColor_Id", c => c.Int(nullable: true));
}
Sign up to request clarification or add additional context in comments.

1 Comment

When setting configurations with the Fluent API (or with decorating classes with DataAnnotations) the changes will be picked up when you add a new migration. Then all you have to do is call update-database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.