0

I had to define a recursive relationship on a composite key. After much trials, I ended up with this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Category>()
            .Property(t => t.WhichAmazon).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        modelBuilder.Entity<Category>()
            .Property(t => t.IdCategory).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        modelBuilder.Entity<Category>()
           .HasKey(c => new {c.WhichAmazon, c.IdCategory})
           .HasOptional(p => p.Children)
           .WithMany()
           .HasForeignKey(c => new { c.WhichChildrenAmazon, c.ChildrenId });                                                                          
    }

for this table

public class Category
{
    // Keys and relationships defined in BooksDataLayer
    [MaxLength(2)]
    public string WhichAmazon { get; set; }
    public int IdCategory { get; set; }        
    public string Name { get; set; }
    [Timestamp]
    public Byte[] TimeStamp { get; set; }        
    public DateTime LastCheck { get; set; }
    public virtual List<Book> Books { get; set; }
    public string WhichChildrenAmazon { get; set; }
    public int? ChildrenId { get; set; }        
    public virtual List<Category> Children { get; set; }
}

While trying to Add-Migration I was constantly having the same error: "Sequence contains no elements". As I was "almost" sure this definition was right, I went ahead a re-created a new Db, WITHOUT migration. Was perfectly OK, no problems with the Db at all. So there is "something" in there which EF 6 does not like. I had a confirmation, as EF power tools bombs if I try to get a schema "Exception has been thrown by the target of an invocation".

I'll see what happens now with migration if I restart from there, but I am afraid to not be able to use anymore with this Db. I do like the tool, a lot, so I hope this can be fixed.

BernardG
  • 1,956
  • 3
  • 17
  • 25

2 Answers2

1

The issue is an invalid configuration of the relationship.

The Fluent API call includes this:

.HasOptional(p => p.Children)
.WithMany()

This is invalid because Children is a collection navigation. The correct config is:

.HasMany(p => p.Children)
.WithOptional()

We are planning to take a fix to provide a better exception message post-EF6.

Rowan Miller
  • 2,090
  • 15
  • 15
0

Opened a bug for this on the EF codeplex site: http://entityframework.codeplex.com/workitem/1015

Pawel
  • 31,342
  • 4
  • 73
  • 104