CTP5:自我引用问题?

时间:2010-12-14 10:33:53

标签: entity-framework-ctp5

有一个简单的模型:

public class Node
{
    public long Id { get; set; }
    public virtual Node Parent { get; set; }
}

以下地图代码将引发异常:

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"));

    }
}

可能是因为它不能自我引用自定义外键名吗?

1 个答案:

答案 0 :(得分:1)

我也这样做,但我不依赖EF获取正确的密钥而且我自己做。所以我的Node课程如下所示:

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;}
}

然后模型构建器的设置如下:

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");