我有一個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);
});
但它看起來 '髒' 到存儲這樣的父母關係。
什麼是正確的方法?
我不確定你的「關係」類是必需的,因爲它只描述關係而沒有其他有意義的數據。我會像這樣建模:'public virtual ICollection RelatedTickets {get;組; },而英孚將執行這些關係。 –
@Mr Anderson它可能有其他數據,您的解決方案我無法控制'臥底'結構和FK名稱 – Ice2burn