Introducing FOREIGN KEY constraint 'FK_dbo.OrderDetails_dbo.Order_OrderId' on table 'OrderDetails' may cause

StackOverflow https://stackoverflow.com/questions/21867538

Pergunta

I'm getting this error message from the PMC:

Introducing FOREIGN KEY constraint 'FK_dbo.OrderDetails_dbo.Order_OrderId' on table 'OrderDetails' 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.

I found a post here on SO with an accepted answer, but it didn't work for me.

These are my tables:

[Table("Order")]
public class Order
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity), Key]
    public int Id { get; set; }

    [Required]
    public string UserId { get; set; }      

    public virtual List<OrderDetails> OrderDetails { get; set; }

    [ForeignKey("UserId")]
    public virtual ApplicationUser User { get; set; }
}


[Table("OrderDetails")]
public class OrderDetails
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity), Key]
    public int Id { get; set; }

    [Required]
    public int OrderId { get; set; }


    [ForeignKey("OrderId")]
    public virtual Order Order { get; set; }
}

The FluentApi:

modelBuilder.Entity<OrderDetails>()
    .HasRequired(u => u.Order)
    .WithMany()
    .WillCascadeOnDelete(false);

If an OrderDetails gets deleted, I don't want the Order to be deleted. But the other way around is fine with me.

So what's wrong with what I tried?

Foi útil?

Solução

I found the problem!

I kept running the command Update-Database which executes the last generated migrations file.

I deleted the last migration file I created, and ran the command Add-Migration again which generated a new file with my latest modelBuilder.Entity<OrderDetails>()... (FluentApi) code changes I made.

Then ran the command Update-Database and it worked!

So what I didn't know was that every time you change something in

protected override void OnModelCreating(DbModelBuilder modelBuilder) { ... },

you need to execute Add-Migration filename again.

Outras dicas

Using .WithMany() without parameter is wrong here. Because Order.OrderDetails represents the inverse navigation property of the relationship you must use...

.WithMany(o => o.OrderDetails)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top