2

当所有代码均未注释时,以下代码会产生外键错误。

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int FavoriteChildId { get; set; }
    public Child FavoriteChild { get; set; }
    //public int WorstChildId { get; set; }
    public Child WorstChild { get; set; }
    public ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    //public int ParentId { get; set; }
    public Parent Parent { get; set; }
}

public class CFContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }
}

如果未指定外键名称但无法编辑模型,则它可以工作。有谁知道如何指定外键名称?

4

1 回答 1

3

遵循命名约定将在上面创建正确的 FK - 您的代码:

public int WorstChildId { get; set; }
public Child WorstChild { get; set; }

是否为 WorstChild 创建 WorstChildId 的 FK。但是,当我尝试上面的代码时,我收到了多个删除路径错误(Parent -> WorstChild -> ChildTable,Parent -> FavoriteChild -> ChildTable)

您可以将其中一个或两个映射设置为在删除时不级联,这将解决您的问题:

public class CFContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithRequiredPrincipal(p => p.WorstChild)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Child>()
         .HasRequired(c => c.Parent)
         .WithRequiredPrincipal(p => p.FavoriteChild)
         .WillCascadeOnDelete(false);
    }
}
于 2012-08-21T13:03:41.930 回答