[英]EF Many-to-Many When Class Already Referenced as FK Not Working
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
. 我想创建一个实体框架
many-to-many
的关系People
与Penguins
在平时的形式PenguinPeople
表保持Person_Id
和Penguin_Id
。 When I generate a migration with the code below, the many-to-many
is not created. 当我使用以下代码生成迁移时,不会创建
many-to-many
。 However, if I comment out the 3 "OwnerId" lines in the Penguin class, the many-to-many
works. 但是,如果我注释掉企鹅类中的3个“ OwnerId”行,则
many-to-many
工程有效。 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. 在您的Person类上,并且仅在两个类上都具有Id属性,那么它应该创建关联表。
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 . 我不知道是否有更简单的方法来执行此操作,但是我被迫使用EF docs中概述的FluentAPI。 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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.