实体框架FOREIGN KEY约束可能导致循环或多个级联路径

时间:2017-10-05 08:03:56

标签: c# asp.net-mvc entity-framework

我使用两个实体。

public class Reservation
    {
        public Reservation()
        {
        }

        [Display(Name = "Id:")]
        [Required]
        public int Id { get; set; }


        public string ClientId { get; set; }
        public virtual User Client { get; set; }

    }

public class User : IdentityUser
{
    public User()
    {
        this.Reservations = new HashSet<Reservation>();
    }

    [Required]
    [Display(Name = "Imię")]

    public string Name { get; set; }
    [Display(Name = "Nazwisko")]
    [Required]
    public string Surname { get; set; }

    [Display(Name = "Data urodzenia")]
    [DataType(DataType.Date)]
    [Required]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime BirthDate { get; set; }

    public virtual ICollection<Reservation> Reservations { get; private set; }
}

当我想删除用户时,我想删除分配给该用户的所有预订。所以我在上下文课上写过。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

            modelBuilder.Entity<Reservation>().HasRequired(x => x.Client)
                                            .WithMany(x => x.Reservations)
                                            .HasForeignKey(x => x.ClientId)
                                            .WillCascadeOnDelete(true);
}

然后在迁移期间,它显示了问题标题中描述的错误。我不能删除Convetions删除一对多,这对我来说是essentail。怎么解决这个问题?

我已经改变了它。

modelBuilder.Entity<Reservation>().HasRequired(x => x.Client)
                                            .WithMany(x => x.Reservations)
                                            .HasForeignKey(x => x.ClientId);

当我想删除用户时。

Message = "The DELETE statement conflicted with the REFERENCE constraint \"FK_dbo.Reservation_dbo.AspNetUsers_ClientId\". The conflict occurred in database \"aspnet-AgrotouristicWebApplication-20170716115104\", table \"dbo.Reservation\", column 'ClientId'.\r\nThe sta...

0 个答案:

没有答案