2
votes

I'm working with code first for a ecommerce project,

I have 2 classes: Category and Products

Relationship is one to many, Category has many products, I want to make the foreign key as required (not null) so, if I add a product, I must enter the categoryid.

When I do so, I get this error:

Introducing FOREIGN KEY constraint 'FK_dbo.Products_dbo.Categories_categoryId' on table 'Products' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Any ideas?

public class Category :IObjectWithState
{
    [Key]
    public int CategoryId { get; set; }
    [Required]
    public string Discription { get; set; }
    public string Notes { get; set; }
    public int ParentCategoryId { get; set; }

    public virtual ICollection<Product> Products { get; set; }
    public virtual ICollection<Discount> Discounts { get; set; }
    public virtual ICollection<ProductList> ProductLists { get; set; }

    [NotMapped]
    public State state { get; set; }
}

public class Product :IObjectWithState
{
    [Key]
    public int ProductId { get; set; }
    [Required]
    public string ProductName { get; set; }
    [Required]
    public string ShortDiscription { get; set; }
    public string LongDiscription { get; set; }

     [Required]
    public bool Active { get; set; }

    [Required]
    public int categoryId { get; set; }
    [ForeignKey("categoryId")]
    public  Category Category { get; set; }

    public ICollection<ProductImage> ProductImage { get; set; }
    public ICollection<Discount> Discount { get; set; }
    public ICollection<Discussion> Duscussion { get; set; }
    public ICollection<ProductAttributeValue> ProductAttributeValue { get; set; }
    public ICollection<ProductListItem> ProductListItem { get; set; }
    public ICollection<ProductSKU> ProductSKU { get; set; }
    public ICollection<RelatedProduct> RelatedProduct { get; set; }
    public ICollection<Review> Review { get; set; }
    public ICollection<ShoppingCart> ShoppingCart { get; set; }
}
1
Are there already items in the products table? - Jonesopolis
the database is not inistialized yet - M.Shahin
when i do so It's relevant for the question to show how you did it. Please show the types and the mapping. - Gert Arnold
i found the solution, AddForeignKey("dbo.Products", "categoryId", "dbo.Categories", "CategoryId", cascadeDelete: false); i set cascadeDelete: to false but i don't know if this is true or not - M.Shahin
true? You mean whether it is correct? Anyhow, it is correct, because there can only be one cascaded delete on a Sql Server table and the cascades can't be circular. If there are too many cascades you have to cut a few. - Gert Arnold

1 Answers

0
votes

i set cascadeDelete: to false in the Migration class