0

我正在尝试在实体中映射 2 个相同类型的属性并收到此错误:

An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Introducing FOREIGN KEY constraint 'FK_dbo.Client_dbo.Messagebox_OutboxId' on table 'Client' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

无法创建约束。请参阅以前的错误。(有关详细信息,请参阅内部异常。)

我知道这个错误与我有 2 个相同类型的道具有关。

如何使用代码优先 + EF fluent API 来完成?

场景:每个Client都有Inbox并且Outbox两者都是Messagebox

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

public class Client : BaseEntity
{
    /// <summary>
    /// Gets or sets Client Alias
    /// </summary>
    public string Alias { get; set; }

    /// <summary>
    /// Gets or sets value indicating if the client was deleted
    /// </summary>
    public bool Deleted { get; set; }

    /// <summary>
    /// Gets or sets client's inbox
    /// </summary>
    public virtual Messagebox Inbox { get; set; }

    /// <summary>
    /// Gets or sets inbox Id
    /// </summary>
    public int InboxId { get; set; }

    /// <summary>
    /// Gets or sets client's outbox
    /// </summary>
    public virtual Messagebox Outbox { get; set; }

    /// <summary>
    /// Gets or sets outbox Id
    /// </summary>
    public int OutboxId { get; set; }
}

public class Messagebox : BaseEntity
{
    public int ClientId { get; set; }

    /// <summary>
    /// Gets or sets the messagebox client
    /// </summary>
    public virtual Client Client { get; set; }
}
4

1 回答 1

0

这个问题与使用两个同名的专业人员无关。它与不愿意创建表之间循环的约束的sql数据库有关。

您可以使用如下流畅的 API 来克服这个问题(请根据您的需要进行调整)

modelBuilder.Entity<Leaves>().HasRequired(l => l.Applicant)
                            .WithMany(bp => bp.LeavesToApply)
                            .HasForeignKey(l => l.ApplicantId)
                            .WillCascadeOnDelete(false);
modelBuilder.Entity<Leaves>().HasOptional(t => t.Approver)
                             .WithMany(bp => bp.LeavesToApprove)
                             .HasForeignKey(u => u.ApproverId)
                             .WillCascadeOnDelete(false);

问题是你必须转向 Cascade。并手动删除东西或删除循环。

于 2013-10-09T15:16:37.657 回答