【问题标题】:How to update foreign key in EF 6 - Code First如何在 EF 6 中更新外键 - 代码优先
【发布时间】:2017-05-11 19:31:18
【问题描述】:

我正在尝试以 ASP.Net MVC 方式更新 EF6(代码优先)中的外键。

让我解释一下:

我的实体

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

我的数据库

表国家有 2 条记录:

  1. Id = 1,名称 = 法国
  2. Id = 2,名称 = 加拿大

表人有 1 条记录:

  1. Id = 1,名称 = Nicolas,Country_Id = 1

我的代码

  // 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"
  }

我的问题

执行前面的代码时,生成的 SQL 永远不会包含 person 表中的 country_Id 字段。

我的“不”问题

我知道在一个 EF 上下文中执行所有这些代码行时它可以完美运行,但在我的情况下,我将拥有来自我的 ASP.Net MVC 页面的数据。 我也想避免检索现有数据并逐个修改每个字段

【问题讨论】:

  • 首先,它是one-to-many 关系。其次,如果您希望能够在修改中包含Country_Id 而无需从数据库中加载数据,则在Person 实体中提供显式Country_Id 属性并设置它而不是导航属性。你可以在 SO 上找到这样的例子。
  • 问题是,设置State = EntityState.Modified 不会将导航属性(关系)设置为已修改,只有标量属性。

标签: c# entity-framework-6 foreign-key-relationship


【解决方案1】:

通过重试@ivan 解决方案,我首先能够做我想做的事。

以下是所做的修改:

 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;

但是现在,从数据库中获取实体时出现异常。 使用此代码:

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

我收到以下 SqlException :“无效的列名 'Country_Id1'。”

是否有任何线索能够检索数据更新外键?

【讨论】:

  • 只有p.Country_Id = 2; 就足够了。
猜你喜欢
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 1970-01-01
相关资源
最近更新 更多