我正在尝试在实体中映射相同类型的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.
无法创建约束。查看以前的错误。 (详见内部异常。)
据我所知,这个错误与我有两个相同类型的道具有关。
如何使用代码优先使用+ 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; }
}
答案 0 :(得分: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。并手动删除或删除循环。