[英]Should I store foreign key table as foreign key ID or the C# model of that table in Entity Framework?
[英]Make a table id its own foreign key entity framework
我想知道是否可以創建一個帶有ID,標簽和引用表ID的外鍵的表。 下面是我要執行的操作示例,但由於無法單獨調用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; }
}
我不知道我是否足夠清楚,如果您需要其他信息,請隨時詢問。
對的,這是可能的。 如果需要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;}
}
我很確定,對於實體框架來說,這足以理解關系。
如果沒有,您可以在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
好的練習:嘗試使用int ParentId
而不是int?
,值為零可能意味着沒有父級。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.