2016-09-27 74 views
1

我有一個Ticket實體:自參照許多一對多的關係

public class Ticket 
    { 
     public int Id { get; set; } 
     public string Title { get; set; } 

     public virtual ICollection<Relation> RelatedTickets { get; set; } 
    } 

我想設置實體框架中的核心多到很多自我的關係,所以我做了兩個一到多關係:

public class Relation 
{ 
    [Required, ForeignKey("TicketFrom")] 
    public int FromId { get; set; } 

    [Required, ForeignKey("TicketTo")] 
    public int ToId { get; set; } 

    public virtual Ticket TicketFrom { get; set; } 
    public virtual Ticket TicketTo { get; set; } 
} 

我試圖用建立的關係流利的API:

 builder.Entity<Relation>() 
       .HasKey(uc => new { uc.FromId, uc.ToId }); 
     builder.Entity<Relation>() 
      .HasOne(c => c.TicketFrom) 
      .WithMany(p => p.RelatedTickets) 
      .HasForeignKey(pc => pc.FromId); 
     builder.Entity<Relation>() 
      .HasOne(c => c.TicketTo) 
      .WithMany(p => p.RelatedTickets) 
      .HasForeignKey(pc => pc.ToId); 

但結果我有一個錯誤:

Cannot create a relationship between 'Ticket.RelatedTickets' and 'Relation.TicketTo', because there already is a relationship between 'Ticket.RelatedTickets' and 'Relation.TicketForm'. Navigation properties can only participate in a single relationship.

可能的解決方案是直接添加父關係TicketEntity

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

    [Required, ForeignKey("ParentRelation")] 
    public Nullable<int> ParentRelationId { get; set; } 

    public virtual Ticket ParentRelation {get;set;} 

    public virtual ICollection<Ticket> RelatedTickets { get; set; } 
    ... 
} 

用流利的API是這樣的:

modelBuilder.Entity<Ticket> => 
{ 
    entity 
     .HasMany(e => e.RelatedTickets) 
     .WithOne(e => e.ParentRelation) 
     .HasForeignKey(e => e.ParentRelationId); 
}); 

但它看起來 '髒' 到存儲這樣的父母關係。
什麼是正確的方法?

+0

我不確定你的「關係」類是必需的,因爲它只描述關係而沒有其他有意義的數據。我會像這樣建模:'public virtual ICollection RelatedTickets {get;組; },而英孚將執行這些關係。 –

+0

@Mr Anderson它可能有其他數據,您的解決方案我無法控制'臥底'結構和FK名稱 – Ice2burn

回答

1

不可能只有一個關係集合。您需要兩張關係票等於TicketFrom,第二張關票等於TicketTo

事情是這樣的:

型號:

public class Ticket 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 

    public virtual ICollection<Relation> RelatedTo { get; set; } 
    public virtual ICollection<Relation> RelatedFrom { get; set; } 
} 

public class Relation 
{ 
    public int FromId { get; set; } 
    public int ToId { get; set; } 

    public virtual Ticket TicketFrom { get; set; } 
    public virtual Ticket TicketTo { get; set; } 
} 

配置:

modelBuilder.Entity<Relation>() 
    .HasKey(e => new { e.FromId, e.ToId }); 

modelBuilder.Entity<Relation>() 
    .HasOne(e => e.TicketFrom) 
    .WithMany(e => e.RelatedTo) 
    .HasForeignKey(e => e.FromId); 

modelBuilder.Entity<Relation>() 
    .HasOne(e => e.TicketTo) 
    .WithMany(e => e.RelatedFrom) 
    .HasForeignKey(e => e.ToId); 

注意,使用母公司的解決方案是不等價的,因爲它會創建one-to-many協會,如果我理解正確,你正在尋找爲many-to-many

+0

其實我正在考慮這個問題,但我的注意力集中在單一的多對多集合上。我想兩種一對多關係最適合我的情況。應該休息一下,謝謝! – Ice2burn