[英]How do I build a self-referencing Model Object for Hierarchical data in asp.net MVC?
[英]How to model self-referencing object type?
说我有一个类Box:
public class Box
{
[Required]
[Key]
int BoxId { get; set; }
string BoxName { get; set; }
}
我希望能够将盒子添加到其他盒子中 - 一个盒子可以有很多盒子或者属于一个盒子,但它也不需要。
我试图在我的项目中对它进行建模:
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中对此进行建模的正确方法是什么?
试试吧。
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;}
}
Fluent API版本。 您可以使用Tyriar建议的注释来完成。 我个人不喜欢我的POCO中的Db垃圾。 所以这是另一种选择......
modelBuilder.Entity<Box>().
HasOptional(e => e.ParentBox).
WithMany().
HasForeignKey(p => p.ParentBoxID);
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.