locked
Setup model: Delete problem RRS feed

  • Question

  • Hi

    I have problem to set up my model with EF6. I have a class Product with a required entity ProductPrice. Every ProductPrice must be linked to a Product. The reason why I want to do this way, is for having a history of all productprice changes. But the Product must have always one ProductPrice. So there are two foreing keys between this two tables, and that's probably the reason why this go wrong.

    Here are may classes.

    Product

    public class Product
        {
            public int Id {get;set;}
            [Required, MaxLength(50)]
            public string Name { get; set; }
            [MaxLength(500)]
            public string Description { get; set; }
            [Required]
            public virtual ProductPrice ProductPrice { get; set; } // FK_dbo.Product_dbo.ProductPrice_Id
            public virtual List<ProductPrice> ProductPrices { get; set; } // ProductPrice.FK_dbo.ProductPrice_dbo.Product_Id
        }

    ProductPrice

    public class ProductPrice
        {
            public int Id { get;set; }
            public decimal Price { get; set; }
            [Required]
            public virtual Product Product { get; set; } // FK_dbo.ProductPrice_dbo.Product_Id
        }

    Now, when I delete a Product, I want that it also deletes all ProductPrices. How can I do this?

    If I just delete the product I receive the error : "- ProductPrice : The ProductPrice field is required.".

    Friday, August 22, 2014 7:30 AM

Answers

  • It's called referential integrity. You cannot delete the parent object/record until all the children objects/records are deleted first. So you need some kind of routine or code to do it, you can setup EF to do cascade deletes you have to look it up or you tell SQL Server to do cascade deletes use Bing or Google.

    • Marked as answer by Fred Bao Monday, September 1, 2014 8:10 AM
    Saturday, August 23, 2014 2:41 AM