First, eliminate the entity framework code with cascade.

ef-code-first entity-framework

Question

How should my domain and LINQ statement be configured so that I may remove 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; }
}

I want to be able to remove Category and cascade that deletion down to all of the child items.

  1. Are there any other characteristics I should add to my domain?
  2. What LINQ statement should you use to remove objects without making a round trip? (I just want a straight deletion; I don't want to choose.)

Is this the only approach to take?

Category category = new Category() {  CategoryId = 1   } ; 
context.AttachTo("Category", category);
context.DeleteObject(category);
context.Savechanges();
1
26
4/2/2011 1:07:23 AM

Accepted Answer

Although you originally cited EF code, which refers to EF 4.1, you then provided an example of object deletion in EF 4. In EF 4.1, the proper method for deleting an object without loading it from the database is:

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

Deflate conventions will also erase all associated products if you didn't make any changes to their setup.OneToManyCascadeDeleteConventions guarantees that all one-to-many relationships are established usingON CASCADE DELETE . There will only be one journey to the database, no further roundtrips.DELETE declaration forCategory with Id = 1.

In the event that you want to erase entirely loaded, a different scenario may arise.Category (when armedProducts If so, EF will produce separate delete statements for each of the following:Product So, with N being the number of goods in the category, you will make N+1 roundtrips to the database. In EF, cascade delete operates like Here. Although it is connected to entity designer, the fundamentals are the same.

41
5/23/2017 12:02:02 PM

Popular Answer

taken from the automatically created VS2010 code:

Category category = db.Categories.Find(id);
db.Categories.Remove(category);
db.SaveChanges();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow