Davide
Davide

Reputation: 1345

Many to many relationship identity error

I'm working on a mvc4 app with ef5 codefirst and I cannot solve this error:

The member with identity 'xxxx' does not exist in the metadata collection.

Update: I saw that I used two different contexts (the navigation object was called thorugh a repository that creates a different DbContext), probably this is a problem. I changed that, but now I get a new error:

Invalid column name 'Brewery_BreweryId'.

In the IntelliTrace I saw that ef tries to

select ..., Brewery_BreweryId from UserProfiles 

This column is not present and shouldn't be present, I want a many to many, not a one-to-many.

I think that is something related to a many to many relation.

this is an example of my code

internal class BreweryConfiguration : EntityTypeConfiguration<Brewery>
{
    public BreweryConfiguration()
    {
      // PK
      HasKey(e => e.BreweryId);

      // FK
      HasMany(e => e.UserProfiles)
        .WithMany()
        .Map(m =>
        {
          m.MapLeftKey("BreweryId");
          m.MapRightKey("UserId");
          m.ToTable("BreweryUserProfiles");
        });

    namespace Project2.DAL.Entities
    {
      [Table("Breweries")]
      public class Brewery : ABrewery
      {
        public int BreweryId { get; set; }
        public ICollection<UserProfile> UserProfiles { get; set; }
      }
    }

    namespace Project1.DAL.Entities
    {
      [Table("UserProfiles")]
      public class UserProfile : IUserProfile
      {

        [Key]
        public int UserId { get; set; }
        ...
      }
}

Join table

Upvotes: 0

Views: 183

Answers (1)

zs2020
zs2020

Reputation: 54524

c.MapLeftKey("ClassB_ID");
c.MapRightKey("ClassA_ID");

should be

c.MapLeftKey("ClassA_ID");
c.MapRightKey("ClassB_ID");

Edit:

You need to define the PK of the ClassB in the configuration as well. In the way you implemented, you may add another derived Configuration for ClassB.

Upvotes: 1

Related Questions