How to update foreign key in EF 6 - Code First

c# entity-framework-6 foreign-key-relationship

Question

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

1
1
5/11/2017 8:01:04 PM

Popular Answer

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 ?

1
5/23/2017 6:27:46 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow