0

親クラスとその子の間の複数の関係を維持するのが困難です。親で 2 つの子参照を作成できるのに、3 番目の子参照を作成できない理由を誰か教えてもらえますか? 以下のコードは、3 番目の参照がコメント アウトされている場合にのみ機能します。

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Child1Id { get; set; }
    public Child Child1 { get; set; }
    public int Child2Id { get; set; }
    public Child Child2 { get; set; }
    //public int Child3Id { get; set; }
    public Child Child3 { 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; }

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

        modelBuilder.Entity<Child>()
         .HasRequired(c => c.Parent)
         .WithRequiredPrincipal(p => p.Child2)
         .WillCascadeOnDelete(false);

        //modelBuilder.Entity<Child>()
        // .HasRequired(c => c.Parent)
        // .WithRequiredPrincipal(p => p.Child3)
        // .WillCascadeOnDelete(false);
    }
}
4

1 に答える 1

1

親エンティティから子エンティティへの 1 対多の関係を作成しようとしているようです。その場合、コードは次のようになります。

public class Parent
{
    public int Id { get; set; }
    public string Name { 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; }
}

ナビゲーション プロパティと外部キーの命名に関する既定の規則に従っている限り、Fluent API でリレーションを指定する必要はありません。Fluent API および/または属性を使用して、非慣習的な名前を使用する関係を構成する必要があります。たとえば、ParentId の名前を変更するには、[ForeignKey("Parent")] 属性でマークする必要があります。

Fluent API を使用する最も一般的な使用例は、カスケード削除を無効にすることです (属性でこれを行う方法はありません)。

于 2012-08-21T20:48:32.000 に答える