Mediator
Mediator

Reputation: 15378

How configure many to many relationship without new entity?

I have two tables Human and Pet. And have table HumanToPet.

How in entity framework do it?

example:

class Human
{
   string Name;
   virtual ICollection<Pet> Pets { get; set; }
}

UPDATE I use mapping (Fluent Configurations)

Upvotes: 0

Views: 58

Answers (2)

Jaycee
Jaycee

Reputation: 3118

public partial class Human
{
   public Human()
   {
      Pets = new List<Pet>();
   }

   public int HumanID { get; set; }
   public string Name{ get; set; }
   public virtual ICollection<Pet> Pets { get; set; }
}

public partial class Pet
{
   public Pet()
   {
      Owners= new List<Human>();
   }

   public int PetID { get; set; }
   public string Name{ get; set; }
   public virtual ICollection<Human> Owners { get; set; }
}

From this structure EF will be able to infer the relationships.

EDIT: Fluent API mapping:

 modelBuilder.Entity<Human>()
 .HasMany(a => a.Pets)
 .WithMany()
 .Map(x =>
 {
   x.MapLeftKey("HumanID");
   x.MapRightKey("PetID");
   x.ToTable("HumanToPet");
  });

Upvotes: 1

codelikeprogrammerwoman
codelikeprogrammerwoman

Reputation: 1569

You need to add references between these tables in your database. After it, your EF model generated in VS will see it.

Upvotes: 0

Related Questions