Entity framework code first delete with cascade

后端 未结 2 1391
青春惊慌失措
青春惊慌失措 2020-12-01 08:16

How do I set up my domain and the LINQ statement so I can delete a record from a database?

public class Category    {
    public int CategoryId { get; set; }         


        
相关标签:
2条回答
  • 2020-12-01 08:30

    Taken from the VS2010 auto generated code:

    Category category = db.Categories.Find(id);
    db.Categories.Remove(category);
    db.SaveChanges();
    
    0 讨论(0)
  • 2020-12-01 08:39

    You mentioned EF code first which means EF 4.1 but you have shown example of deleting object in EF 4. Correct approach to delete object in EF 4.1 without loading it from database is:

    var category = new Category() { CategoryId = 1 };
    context.Categories.Attach(category);
    context.Categories.Remove(category);
    context.SaveChanges();
    

    If you didn't change anything in configuration of defalut conventions it will also delete all related products because OneToManyCascadeDeleteConventions ensures that all one-to-many relations are created with ON CASCADE DELETE. There will be no additional roundtrips to database - only single DELETE statement for Category with Id = 1.

    The different situation can occure if you want to delete fully loaded Category (with loaded Products navigation property) in such case EF will create separate delete statement for each Product so you will have N+1 roundtrips to database where N is number of products in category. Here is how cascade delete works in EF. It is related to entity designer but described principles are the same.

    0 讨论(0)
提交回复
热议问题