0

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)

Mediator
  • 14,951
  • 35
  • 113
  • 191

2 Answers2

1
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");
  });
Jaycee
  • 3,098
  • 22
  • 31
0

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

codelikeprogrammerwoman
  • 1,429
  • 3
  • 14
  • 17