1

クラス Box があるとします。

public class Box
{
    [Required]
    [Key]
    int BoxId { get; set; }
    string BoxName { get; set; }
}

ボックスを他のボックスに追加できるようにしたい - ボックスは多くのボックスを持つことも、1 つのボックスに属することもできますが、どちらも必要ありません。

私は自分のプロジェクトで次のようにモデル化しようとしました:

public class Box
{
    [Required]
    [Key, ForeignKey("ParentBox")]
    int BoxId { get; set; }
    string BoxName { get; set; }
    int ParentBoxId { get; set; }
    Box ParentBox { get; set; }
    List<Box> Boxes {get; set;}
}

ただし、この質問で対処する次のエラーが表示されます。

「App.Core.Set_ParentSet」関係のプリンシパル エンドを特定できません。追加された複数のエンティティが同じ主キーを持つ場合があります。

ForeignKey 属性を削除するとデータベースを構築できますが、カスケード削除が機能しません。

ボックスがボックスに属しているかどうか、またはボックスを持っているかどうかは、アプリケーションで常に変化するため、ChildBox または ParentBox 用に別のクラスを作成したくありません。

これをEFでモデル化する適切な方法は何ですか?

4

3 に答える 3

3

これを試してみてください。

public class Box
{
    [Required]
    [Key]
    public int BoxId { get; set; }

    public string BoxName { get; set; }

    public int ParentBoxId { get; set; }

    // The foreign key for the Box that points at ParentBox.BoxId  (the [Key])
    [ForeignKey("ParentBoxId")]
    public Box ParentBox { get; set; }

    // The foreign key for the Boxes that point at this.BoxId (the [Key])
    [ForeignKey("ParentBoxId")]
    public virtual ICollection<Box> Boxes {get; set;}
}
于 2013-03-02T09:20:21.823 に答える
1

BoxIDに問題があります。主キーであると同時に外部キーでもありますか?例については、 http://msdn.microsoft.com/en-us/data/gg193958を参照してください。

外部キーの代わりにInversePropertyを使用できます。これにより、冗長性の量が減少します。

   [Table("Box")]
public class Box
{

    [Required]
    [Key]
    [Column("BoxId")]
    public virtual int BoxId { get; set; }

    [Column("Name")]
    public virtual string Name { get; set; }

    [Column("ParentBoxID")]
    public virtual int? MyParentBoxId { get; set; }

    [ForeignKey("MyParentBoxId")]
    public virtual Box Parent { get; set; }

    [InverseProperty("Parent")]
    public virtual ICollection<Box> Boxes { get; set; }

}
于 2013-03-02T09:11:11.390 に答える
1

FluentAPIバージョン。Tyriarが提案するように、注釈を使用してそれを行うことができます。私は個人的にPOCOのDbジャンクが好きではありません。だからここに代替案があります...

modelBuilder.Entity<Box>().
  HasOptional(e => e.ParentBox).
  WithMany().
  HasForeignKey(p => p.ParentBoxID);
于 2013-03-02T09:35:07.283 に答える