简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM