简体   繁体   中英

Entity Framework Code First - 2 Entities of the Same Type

I'm trying to map 2 properties of the same type in entity and getting this error:

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.

Could not create constraint. See previous errors. (See inner exception for details.)

I understand that this error related to the fact I'm having 2 props of the same type.

How can it done using code first + EF fluent API?

The scenario: Each Client has Inbox and Outbox which both are 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; }
}

This issue has not to do with using two pros with same name. It has to do with sql database not willing to create constraints that are cycles between tables.

You can overcome this with fluent API like below (please adjust to your needs)

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);

The thing is that you have to turn of Cascade. And manually delete things or remove the cycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM