none
How can I map this navigation property with Code First? RRS feed

  • Question

  • I have two entities. The parent has many children, but also stores a reference to the most recent child added.

    public class Foo 
    {
      public int Id { get; set; }
      public ICollection<Bar> Bars { get; set; }
    
      public int? CurrentBarId { get; set; }
      public virtual CurrentBar CurrentBar { get; set; } 
    }
    
    public class Bar 
    {
      public int Id { get; set; }
      public int FooId { get; set; }
      public virtual Foo Foo { get; set; }
    }
    

    When I add the CurrentBarId property everything is persisted correctly. However, when I add the CurrentBar property an exception is thrown when the Bar is created: "Invalid column name 'Foo_Id'."

    I tried playing around with the model builder and ended up with this:

    modelBuilder.Entity<Foo>()
      .HasOptional(x => x.CurrentBar)
      .WithOptionalDependent()
      .Map(map =>
      {
        map.ToTable("Bar").MapKey("CurrentBarId");
      });

    Now I get the error:

    error 3034: Problem in mapping fragments starting at lines 213, 442:An entity from one EntitySet is mapped to a row that is also mapped to an entity from another EntitySet with possibly different key. Ensure these two mapping fragments do not map two unrelated EntitySets to two overlapping groups of rows.

    How should I be trying to do this?  Thanks.

    Friday, July 1, 2011 12:07 AM

All replies

  • "Invalid column name 'Foo_Id'"

    Do you use FooId or Foo_Id ? Maybe there is a problem in naming.

    Regards

    Friday, July 1, 2011 8:12 AM