简体   繁体   English

如何在EF 6中更新外键-代码优先-一对多关系

[英]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. 基于此问题提供的解决方案: 如何在EF 6-Code First中更新外键 ,我能够使用id字段更新我的外键。

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'." 我收到以下SqlException:“无效的列名'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 ? 用另一种方式问,是否可以同时使用导航属性来简化我的实体的使用,以及是否可以使用外键的ID来更新我的从属实体?

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. 那可能是因为实体框架试图基于导航属性Country in Person实体创建新的外键。

I think you should annotate Country_Id property with ForeignKey attribute as below. 我认为您应该使用ForeignKey属性注释Country_Id属性,如下所示。

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. 但是,如果您遵循以下ef命名约定来命名属性,则无需注释它。

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. 注意:您可能需要运行数据库迁移或需要重新创建数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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