Reputation: 11
there is a simple model:
public class Node
{
public long Id { get; set; }
public virtual Node Parent { get; set; }
}
the following map code will throw an exception:
public class NodeContext : DbContext
{
public DbSet<Node> Nodes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Node>().HasOptional(n => n.Parent).WithMany().IsIndependent().Map(m => m.MapKey(p => p.Id, "ParentId"));
}
}
Could it be that it is not capable of self-reference custom foreign key name do it?
Upvotes: 1
Views: 271
Reputation: 68506
I do the same, but I don't rely on EF getting the keys correct and I do it myself. So my Node
class looks like the following:
public class Node
{
public int Id {get;set;}
public int ParentId {get;set;}
public virutal Node Parent {get;set;}
public virtual ICollection<Node> Children {get;set;}
}
And then the ModelBuilder is setup as follows:
builder.Entity<Node>().HasKey(x => x.Id);
builder.Entity<Node>()
.HasOptional(s => s.Parent)
.WithMany(c => c.Children)
.HasForeignKey(s => s.ParentId);
builder.Entity<Node>().ToTable("Node");
Upvotes: 1