0

これに対する答えが見つからないようですので、誰かが助けてくれることを願っています。同じモデルの他のアイテム内にネストできる次のモデルがあり、n 層のデータセットを効果的に作成します。私のモデルは次のように書かれています:

public partial class Resource
{
  [Key]
  public int ResourceID { get; set; }
  [Display(Name = "Parent Resource")]
  public int? ParentResourceID { get; set; }
  public virtual Resource ParentResource { get; set; 
  [Display(Name = "Resource Name")]
  public string Name { get; set; }
  public bool Deleted { get; set; }
}

ParentResourceID は NULL に設定できます。これは、アイテムがレベル 1 にあり、親を持たないことを意味します。

ただし、親リソースが割り当てられているデータベースから項目を要求すると、ParentResource オブジェクトは常に空になります。

[ForeignKey] と [InverseProperty] のアイデアを多数試しましたが、うまくいきませんでした。

モデルが実際の ParentResourceID が仮想オブジェクトの ResourceID と等しいことを認識できるように、何かをマップする必要がありますか? その場合、どうすればよいですか?

4

1 に答える 1

0

I would use the Fluent API to configure this. It is a lot more flexible than using the attributes on your entity properties. It would look something like this.

 this.HasOptional(l => l.ParentResource)
  .WithMany(p => p.Children)
  .HasForeignKey(l => l.ParentId);

What is not clear from your model is whether a parent can have multiple children. Assuming multiple children you need to add a property like this to your model.

public virtual List<Resource> Children {get; set;}
于 2013-02-01T20:09:52.153 に答える