Wilka
Wilka

Reputation: 29613

Migrating form Navigation Property to Foreign Key in Entity Framework

I currently have an EF entity with a navigation properly, something like:

public class Person
{
  public int Id { get;set;};
  public string Name { get;set;};
  public virtual Office WorkingAt { get;set;}
}

public class Office
{
  public int Id {get;set;}
  public string Name { get;set;}
  public string Address {get;set;}
}

I'd like to change from using a "Navigation Property" for WorkingAt to a simple reference to the Id of the Office object.

How do I go about doing this? I'm not clear on what the migration path should be.

I already have data in my database, and the Person table contains an Office_Id column which I'd like to keep using.

Upvotes: 3

Views: 971

Answers (2)

jpgrassi
jpgrassi

Reputation: 5762

As discussed here with Entity Framework Code First you need to have at least one navigation property for your relationship to work.

But if you'd like to keep your navigation property (for the purposes of avoiding dealing with migrations) and just add a foreign key to your model, than you can do it using the ForeignKey DataAnnotation. This way you explicitly tell Entity Framework of your intentions.

public class Person
{
  public int Id { get;set;}
  public string Name { get;set;}

  [ForeignKey("Office")]
  public int OfficeId { get; set; }

  public virtual Office WorkingAt { get;set;}
}

Another way one can achieve this is adding the ForeignKey annotation to the navigation property and tell which property will act as the Foreign Key:

public class Person
{
  public int Id { get;set;}
  public string Name { get;set;}      

  public int OfficeId { get; set; }

  [ForeignKey("OfficeId")]
  public virtual Office WorkingAt { get;set;}
}

Upvotes: 2

Rob
Rob

Reputation: 27367

You don't need to represent the field as a foreign key in your code. Since you don't have a navigation property, it's simply a column on the Person table as far as EF is concerned. You're not using a navigation property, whether it's a foreign key or not is irrelevant, as you can no longer use it to automatically join to the Office table.

Since it's already using Office_Id as your foreign key in the database, you simply need to do this:

public class Person
{
    public int Id { get;set;}
    public string Name { get;set;}

    public int Office_Id  { get; set; }
}

Then run Add-Migration. It'll probably try to remove the foreign key in the Up method (and add it back in the Down method). Remove both these lines referring to foreign keys. Ideally, your Up and Down methods should be empty.

Upvotes: 2

Related Questions