Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

Entity framework code first delete with cascade

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; }
    public string Name { get; set; }

    public List<Product> Products{ get; set; }

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

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

What I'd like to do is delete Category and be able to cascade the delete to all the child products.

  1. Is there any other additional attributes needed in my domain?
  2. What is the LINQ statement to delete objects without doing a round trip? (I do not want to select, just a direct delete).

Is this the only way to do this?

Category category = new Category() {  CategoryId = 1   } ; 
context.AttachTo("Category", category);
context.DeleteObject(category);
context.Savechanges();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...