问题
I have a simple Entry class model
public class Entry
{
public int Id { get; set; }
public DateTime Modified { get; set; }
public DateTime Created { get; set; }
// Related entries
public virtual ICollection<Entry> RelatedEntries { get; set; }
// The nodes this entry contains
public virtual ICollection<Node> Nodes { get; set; }
// The category this entry is located in
public virtual Category Category { get; set; }
}
I want my entry to be able to have a list of related entries, the problem is it just adds a FK Entry_id to the Entries table, I want to create a new table, which holds a many to many relationship, for example
Entry_Id | Related_Entry_Id
01 | 02
01 | 03
01 | 06
02 | 04
So that would make entry 01 related to 02, 03 and 06, and entry 02 with 04.
回答1:
You can specify with Fluent API that the relationship is of type many-to-many (and not a one-to-many relationship which EF assumes by default):
public class MyContext : DbContext
{
//...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Entry>()
.HasMany(e => e.RelatedEntries)
.WithMany()
.Map(m =>
{
m.MapLeftKey("Entry_Id");
m.MapRightKey("Related_Entry_Id");
m.ToTable("EntryRelations");
});
}
}
来源:https://stackoverflow.com/questions/12252868/ef5-code-first-force-many-to-many-recursive-relationship