Water Cooler v2
Water Cooler v2

Reputation: 33880

Missing fields in relationship table when using Code First

I am using Code First with Entity Framework 6.1.2.

I have two entity / master tables like so:

[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
  ...
}

And I just defined a relationship table between them like so:

// 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
  ...

}

And I updated the Foos entity definition like so:

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

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

  // More fields
  ...
}

But when I run the update-database commandlet in PowerShell / Nuget Package Console, the updated database's FooBars table only has the following columns:

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

It does not have the ThisRelationshipGoingGood field or any other fields I added to the FooBars entity.

How do I have the FooBars table have the remaining fields I defined?

Upvotes: 0

Views: 109

Answers (2)

Iraj
Iraj

Reputation: 1522

use this :

[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
  ...

}

and in consol package manager , before update-database command , first add-migration , then use update-database command.

Upvotes: 1

kodeaben
kodeaben

Reputation: 2065

Have you used add/enable-migration ?? look at this tutorial https://msdn.microsoft.com/en-us/data/jj591621.aspx I hope this helps.

Upvotes: 0

Related Questions