开发者

Cascade delete in EF4 CTP5 Code First performs update on child records

Using the method described here, I am开发者_开发问答 attempting to delete a parent record and all the associated child records. However, what happens is the parent is deleted as expected, but child record key field is updated to NULL instead of being deleted.

I also set the child table foreign key's Delete Rule to Cascade, and deleting from the parent table in SQL Server Management performs the cascade delete as expected.

I started by following this walkthough, and modifying the code to perform a delete.

this is the code:

 using (var db = new ProductContext())
 {
     var food = db.Categories.Find("FOOD");
     ((IObjectContextAdapter)db).ObjectContext.LoadProperty(food, f => f.Products);

     db.Categories.Remove(food);
    int recordsAffected = db.SaveChanges();

Is there something I'm missing? Or is orphaned child records the intended result?


The association between Product and Category has been configured as optional due to the fact that the foreign key property on Product class (i.e. Product.CategoryId) has a nullable type (i.e. string). To make this association required so that the child entity is get deleted as a result of deleting the parent you need to mark CategoryId as Required as I did in the following code:

public class Category
{
    public string CategoryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }

    [Required]
    public string CategoryId { get; set; }
    public virtual Category Category { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜