Entity Framework: Multiple navigation properties from same model causing error when adding migration

asp.net-core c# entity-framework entity-framework-core

Question

I have a model called TypeListItem w/ three properties (Id, TypeListId, Name) that contains a bunch of lists.

For example:

ProductType: Strong, Weak, Medium

ProductCategory: Category 1, Category 2, Category 3

I have a Product model that looks like this:

public int Id {get; set;}
public string Name {get; set;}
public int ProductTypeId {get; set;}  
public int ProductCategoryId {get; set;}

// Navigation Properties
public TypeListItem ProductType {get; set;}
public TypeListItem ProductCategory {get; set;}

However, when I go to add a migration and then dotnet ef database update' I get an error:

Introducing FOREIGN KEY constraint : FK_Product_TypeListItem_ProductCategoryId on table 'Product' may cause cycles or multiple cascade paths.

I also have the following using fluent api:

builder.Entity<Product>()
    .Property(p => p.ProductTypeId)
    .IsRequired();
builder.Entity<Product>()
    .Property(p => p.ProductCategoryId)
    .IsRequired();

I believe the error is because I have two navigation properties that use the same object and both are required.

Any recommendations? Is there something wrong with my model?

Does something like this make sense for ef core?

    builder.Entity<Product>()
        .HasOne(p => p.ProductType)
        .WithOne().OnDelete(DeleteBehavior.Restrict);

    builder.Entity<Product>()
        .HasOne(p => p.ProductCategory)
        .WithOne().OnDelete(DeleteBehavior.Restrict);
1
1
11/20/2016 3:58:19 AM

Popular Answer

You need to use OnDelete(DeleteBehavior.Restrict) as shown below.

Note :

Restrict : The delete operation is not applied to dependent entities. The dependent entities remain unchanged.

builder.Entity<Product>()
    .Property(p => p.ProductTypeId)
    .WithOne()
    .OnDelete(DeleteBehavior.Restrict);

builder.Entity<Product>()
    .Property(p => p.ProductCategoryId)
    .WithOne()
    .OnDelete(DeleteBehavior.Restrict);

You can see more here : Cascade Delete

1
11/20/2016 6:26:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow