1

So I believe I screwed up my initial models and missed an ID and Foreign Key property. Entity Framework has figured this out anyway.... but now I want to fix up my models to correctly reflect this.

Originally my models were:-

public Season
{
    public int SeasonId {get; set;}
    public int Year {get; set;}

    public virtual ICollection<MatchFixture> MatchFixtures {get; set;}
}

public MatchFixture
{
    public int MatchFixtureId {get; set;}

    public int Round {get; set;}
    public string HomeTeam {get; set;}
    public string AwayTeam {get; set;}
}

Now I believe I should have MatchFixture have properties so it points to the Season that contains it, adding the following properties to MatchFixture.

public int SeasonId {get; set;}
public Season Season {get; set;}

But the issue is that my database already has a column in my MatchFixtures called Season_SeasonId. This is a nullable integer column, obviously coming from my containing collection in Season. If I originally had the properties above in MatchFixture, the column would just be called SeasonId, and be a non-nullable integer column.

What I want is for the values in that column to be transferred to my new column....

  1. How do I do this using CodeFirst migrations? Should I rename the column, and change it to non-nullable, and we're done?
  2. Should I even be adding these properties? I find it makes my code easier too navigate 'up the hierarchy' (i.e which Season does this MatchFixture exist in? matchFixture.Season, but I feel this is part of a bigger problem where my understand of Entity Framework is hampering me.
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Sean Holmesby
  • 2,135
  • 3
  • 23
  • 34

1 Answers1

0

You can do it in one step, but you need to make sure first that there is no NULL value of Season_SeasonId in the database, if there is you need to do something about it, either remove it or set the foreign key value.

Just add these properties on MatchFixture.

public int SeasonId { get; set; }
public Season Season { get; set; }

Then enable, add and run the migration.

PM> Enable-Migrations
PM> Add-Migration AddMatchFixtureFK
PM> Update-Database

Then you have everything you need.

If you check the AddMatchFixtureFK migration, the Up method will have all steps necessary.

- Drop Foreign Key
- Drop Index
- Rename Column
- Alter Column (to non null-able)
- Create Index
- Add Foreign Key

Whether you need to add those properties or not, it has been explained in this post. But one thing I found out that adding those navigation properties (id and reference) will make data manipulation and seed data become much easier. For example, you can add new MatchFixture to existing Season just by setting the SeasonId.

Community
  • 1
  • 1
Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67