nicV
nicV

Reputation: 680

Entity Framework: "Invalid column name" error with many to many mapping

I have a database which I am trying to implement in Entity Framework. Two of the tables have a many to many relationship and it seems that entity framework is trying to create a column name which doesn't exist. It insists that there is an:

Invalid column name 'Shipment_Id'.

However, nowhere in my code or database is there that column. The two tables are Allocation and Shipment, joint by ShipmentAllocation.

Here are the configurations: Allocation:

public AllocationConfiguration()
    {
        this.Property(x => x.Id).HasColumnName("AllocationId");
        this.HasKey(x => x.Id);

        this.Property(x => x.FulfillmentCenter).HasMaxLength(50);
        this.Property(x => x.DateCreated);
        this.Property(x => x.DateModified);
        this.Property(x => x.ModifiedBy).HasMaxLength(50);

        HasMany(x => x.OrderItems)
            .WithOptional(x => x.Allocation)
            .Map(x => x.MapKey("AllocationId"));

        this.HasMany(a => a.Shipments)
            .WithMany()
            .Map(x =>
                {
                    x.MapLeftKey("AllocationId");
                    x.MapRightKey("ShipmentId");
                    x.ToTable("ShipmentAllocation");
                });

    }

Shipment:

/// <summary>
    /// Initializes a new instance of the <see cref="ShipmentConfiguration"/> class.
    /// </summary>
    public ShipmentConfiguration()
    {
        this.Property(x => x.Id).HasColumnName("ShipmentId");
        this.HasKey(x => x.Id);

        this.Property(x => x.DateCreated);
        this.Property(x => x.DateModified);
        this.Property(x => x.ModifiedBy).HasMaxLength(50);

        this.HasMany(x => x.Cartons)
            .WithRequired(x => x.Shipment)
            .Map(x => x.MapKey("ShipmentId"));
    }

I am really not sure what is wrong, I have scoured stackoverflow and other forums and everything seems to suggest that what I have is correct.

Upvotes: 2

Views: 3092

Answers (1)

nicV
nicV

Reputation: 680

Somehow I managed, after a day of struggling to figure it out 10 minutes after asking on here.

The fix was to change the configuration of Allocation to:

this.HasMany(a => a.Shipments)
    .WithMany(x => x.Allocations)
    .Map(x =>
         {
             x.MapLeftKey("AllocationId");
             x.MapRightKey("ShipmentId");
             x.ToTable("ShipmentAllocation");
          });

I.e add in x => x.Allocations to WithMany().

I am not 100% sure why this was needed, I think it forced Entity Framework to use my column names instead of trying to create them itself. If anyone else has more input please share!

Upvotes: 7

Related Questions