nmariot
nmariot

Reputation: 495

How to update foreign key in EF 6 - Code First

I'm trying to update a foreign key in EF6 (Code First) in an ASP.Net MVC manner.

Let me explain :

My entities

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

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

My database

Table Countries with 2 records :

  1. Id = 1, Name = France
  2. Id = 2, Name = Canada

Table People with 1 record :

  1. Id = 1, Name = Nicolas, Country_Id = 1

My code

  // In a MVC application, these class has been retrieved via EF in a previous page. So now, we've lost all "proxy" informations
  var p = new Person() { Id = 1, Name = "Nicolas" };

  // Change country
  p.Country = new Country() { Id = 2, Name = "Canada" };

  // Persist all in DB
  using (var db = new TestDbContext())
  {                
      db.Persons.Attach(p); // Reattach to EF context
      db.Entry<Person>(p).State = EntityState.Modified; // Flag modified state
      db.SaveChanges(); // Generate only modification on field "name"
  }

My issue

When the previous code is executed, the generated SQL never include the country_Id field from the person table.

My "not" issue

I know that it works perfectly when doing all these lines of codes in one EF context but in my case, I will have the data coming from my ASP.Net MVC page. I would also like to avoid to retrieve the existing data and modify each field one by one

Upvotes: 2

Views: 2372

Answers (1)

nmariot
nmariot

Reputation: 495

By retrying @ivan solution, I was first able to do what was wanted.

Here are the modifications done :

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

 // ...

 // Change country
 p.Country = new Country() { Id = 2, Name = "Canada" };
 p.Country_Id = 2;

But now, I get an exception when getting entities from the database. Using this code :

 // Retrieve data first
 using (var db = new TestDbContext())
 {
      var p2 = db.Persons.First();
 }

I get the following SqlException : "Invalid column name 'Country_Id1'."

Does anyone have any clues to be able to retrieve data and to update the foreign key ?

Upvotes: 1

Related Questions