How to update foreign key in EF 6 - Code First - One to many relationship

c# entity-framework-6 sql-server

Question

Based on the solution provided in this question : How to update foreign key in EF 6 - Code First, I'm able to update my foreign key using the id field.

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 ? Asked in another way, is it possible to use both the navigation property to ease the use of my entity and the id of the foreign key to be able to update my dependent entity ?

My entities

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; }
}

public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
}
1
1
6/6/2017 8:07:42 AM

Accepted Answer

That might be because entity framework is trying to create new foreign key based on navigation property Country in Person entity.

I think you should annotate Country_Id property with ForeignKey attribute as below.

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    [ForeignKey("Country_Id")]
    public virtual Country Country { get; set; }
    public int Country_Id { get; set; }
}

However if you follow the ef naming convention for naming property as below, you don't need to annotate it.

Any property with the same data type as the principal primary key property and with a name that follows one of the following formats represents a foreign key for the relationship: '', '', or ''

You may read more from here

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

Note: you might need to run database migration or need to recreate database.

2
6/6/2017 8:46:39 AM


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