简体   繁体   English

使表ID成为自己的外键实体框架

[英]Make a table id its own foreign key entity framework

I wanted to know if it was possible to create a table with an id, a label and a foreign key referring to the id of the table itself. 我想知道是否可以创建一个带有ID,标签和引用表ID的外键的表。 Below is the example of what I would like to do but that does not work because the public virtual RubricFo can not be called by itself. 下面是我要执行的操作示例,但由于无法单独调用public virtual RubricFo而无法正常工作。

public class RubricFO
{
   [Key, Required]
   public int IdRubricFO { get; set; }

   [MaxLength(250)]
   public string LabelRubricFO { get; set; }

   public bool IsActif { get; set; }

   public int RankDisplay { get; set; }

   [ForeignKey("IdRubricFO")]
   public int IdRubricFO_Fk { get; set; }
   public virtual RubricFO RubricFO { get; set; }

   public int IdStructure { get; set; }

   [ForeignKey("IdStructure")]
   public virtual Structures Structures { get; set; }
}

I do not know if I am clear enough if you need additional info do not hesitate to ask. 我不知道我是否足够清楚,如果您需要其他信息,请随时询问。

Yes, it is possible. 对的,这是可能的。 You see this if you want a Tree structure, where every node of the Tree has zero or more SubNodes , no ParentNode if it is a top node, or one ParentNode if it is a SubNode . 如果需要Tree结构,则可以看到此结构,其中Tree的每个节点都有零个或多个SubNodes ;如果是顶层节点,则没有ParentNode如果是ParentNode ,则只有一个SubNode

class Node
{
    public int Id {get; set;}

    // every Node has zero or more subNodes:
    public virtual ICollection<Node> SubNodes {get; set;}

    // every Node is the subNode of zero or one ParentNode, using foreign key
    public int? ParentId {get; set;}         // null if it is a Top Node
    public virtual Node Parent {get; set;}
}

I'm pretty sure, that this is enough information for entity framework to understand the relations. 我很确定,对于实体框架来说,这足以理解关系。

If not, you can use fluent API in your DbContext to inform entity framework about the model 如果没有,您可以在DbContext使用fluent API通知实体框架有关模型的信息

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     // build table Nodes:
     modelBuilder.Entity<Node>()
         .HasKey(node => node.Id)                // not needed, I followed the conventions
         .HasOptional(node => node.Parent)       // every node table has an optional Parent
         .WithMany(node => node.SubNodes)        // every Parent Node has zero or more SubNodes
         .HasForeignKey(node => node.ParentId);  // the foreign key to the parent node

Nice exercise: try int ParentId instead of int? 好的练习:尝试使用int ParentId而不是int? , a zero value could mean there is no parent. ,值为零可能意味着没有父级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM