I am trying to create an Entity Framework many-to-many
relationship between People
and Penguins
in the form of the usual PenguinPeople
table holding Person_Id
and Penguin_Id
. When I generate a migration with the code below, the many-to-many
is not created. However, if I comment out the 3 "OwnerId" lines in the Penguin class, the many-to-many
works. What gives? They should be independent.
public class Penguin
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public long OwnerId{ get; set; } //works if I comment this out
[ForeignKey("OwnerId")] //works if I comment this out
public Person Person{ get; set; } //works if I comment this out
public virtual ICollection<Person> PenguinTrainers{ get; set; }
}
public class Person
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public virtual ICollection<Person> People{ get; set; }
}
If you have an
ICollection<Penguin> AssignedPenguins { get; set; }
on your Person class and just the Id properties on both classes then it should create the associative table.
I don't know if there is an easier way to do this, but I was forced to use FluentAPI as outlined in the EF docs . Example is just from docs, since obviously my penguin/person models were just made-up replacements for the ones actually causing the problem:
modelBuilder.Entity<Post>()
.HasMany(p => p.Tags)
.WithMany(t => t.Posts)
.Map(mc =>
{
mc.ToTable("PostTags");
mc.MapLeftKey("Post_Id");
mc.MapRightKey("Tag_Id");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.