【问题标题】:ASP.Net MVC Recursive Model with Parent ID带有父 ID 的 ASP.Net MVC 递归模型
【发布时间】:2013-02-01 19:54:49
【问题描述】:

我似乎无法找到答案,所以希望有人能提供帮助。我有以下模型,可以嵌套在同一模型的其他项目中,有效地创建一个 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,如果是,我该怎么做?

【问题讨论】:

    标签: asp.net-mvc-3 recursion model ef-code-first foreign-keys


    【解决方案1】:

    我会使用Fluent API 来配置它。它比在实体属性上使用属性要灵活得多。它看起来像这样。

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

    您的模型中不清楚的是父母是否可以有多个孩子。假设有多个孩子,您需要将这样的属性添加到您的模型中。

    public virtual List<Resource> Children {get; set;}
    

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2014-12-16
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 2016-10-02
      相关资源
      最近更新 更多