使用Code First时缺少关系表中的字段

时间:2015-08-21 14:18:58

标签: entity-framework ef-code-first code-first ef-migrations

我正在使用Code First和Entity Framework 6.1.2。

我有两个实体/主表,如下所示:

[Table("Foos")]
public class Foo
{
  [Key]
  public string Id { get; set;}

  // More fields
  ...
}

[Table("Bars")]
public class Bar
{
  [Key]
  public int Id { get; set;}

  // More fields
  ...
}

我刚刚定义了他们之间的关系表:

// Each foo can have zero or more bars.
[Tables("FooBars")]
public class FooBar
{
  [Key]
  public int Id { get; set;}

  [ForeignKey("Foo")]
  public string FooId { get; set;}
  public Foo Foo { get; set;}

  [ForeignKey("Bar")]
  public int BarId { get; set; }
  public Bar Bar { get; set;}

  // Extra fields in this relationship table
  public bool ThisRelationshipGoingGood { get; set;}

  // More fields
  ...

}

我更新了Foos实体定义,如下所示:

[Table("Foos")]
public class Foo
{
  [Key]
  public string Id { get; set;}

  public ICollection<Bar> Bars { get; set; }

  // More fields
  ...
}

但是当我在PowerShell / Nuget Package Console中运行update-database命令行开关时,更新后的数据库的FooBars表只有以下列:

FooBars
----------
FooId (string)
BarId (int)

它没有ThisRelationshipGoingGood字段或我添加到FooBars实体的任何其他字段。

如何让FooBars表包含我定义的剩余字段?

2 个答案:

答案 0 :(得分:1)

使用它:

[Table("Foos")]
public class Foo
{
  [Key]
  public string Id { get; set;}

  [InverseProperty("Foo")]
  public ICollection<FooBar> FooBars { get; set; }

  // More fields
  ...
}

[Table("Bars")]
public class Bar
{
  [Key]
  public int Id { get; set;}

  [InverseProperty("Bar")]
  public ICollection<FooBar> FooBars { get; set; }
  // More fields
  ...
}

[Tables("FooBars")]
public class FooBar
{
  [Key]
  public int Id { get; set;}

  public string FooId { get; set;}

  [ForeignKey("FooId")]
  [InverseProperty("FooBars")]
  public Foo Foo { get; set;}


  public int BarId { get; set; }

  [ForeignKey("BarId")]
  [InverseProperty("FooBars")]
  public Bar Bar { get; set;}

  // Extra fields in this relationship table
  public bool ThisRelationshipGoingGood { get; set;}

  // More fields
  ...

}

并在consol包管理器中,在update-database命令之前,先进行add-migration,然后使用update-database命令。

答案 1 :(得分:0)

您是否使用过添加/启用迁移? 看看这个教程https://msdn.microsoft.com/en-us/data/jj591621.aspx 我希望这会有所帮助。