C # is the best way to delete a large collection in EntityFramework

I have the following classes with a one-to-many relationship.

public class Category
{
    public Category()
    {
        this.Products = new List<Product>();
    }
    public int Id {get;set;}
    public string Name {get;set;}
    public ICollection<Product> Products {get;set;}
}

public class Product
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int CategoryId {get;set;}
    public Category Category {get;set;}
}

My datacontext is as shown below:

public class MyContext : DbContext
{
    public virtual IDbSet<Category> Categories { get; set; }
    public virtual IDbSet<Product> Products { get; set; }
}

I would like to replace the existing collectino products for the category with a new collection of categories. What is the best way to do this in EF?

Basically, from the provided collection, if productid is specified, update if the entity is not available, then add a new product. if not listed remove from the database.

Here is what I am trying to do.

using (var dbCtx = new MyDBEntities())
{
    //1- Get data from database
    //2- Find newly added items
    //3- Find deleted items
    //4- Find modified
    //5- Mark all added items entity state to Added
    //6- Mark all deleted item entity state to Deleted
    //7- Apply modified items current property values to existing property values
    dbCtx.SaveChanges();
}
+4
source share
1 answer

Pay attention to the following lines:

  • Get data from a database
  • Find Newly Added Items
  • Search for deleted items
  • Find modified

, ?   .

EntityGraphOperations Entity Framework Code First. . github, code-project nuget. InsertOrUpdateGraph Added Modified. DeleteMissingEntities , , .

// This will set the state of the main entity and all of it navigational 
// properties as `Added` or `Modified`.
context.InsertOrUpdateGraph(category)
       .After(entity =>
       {
            // And this will delete missing products.
            entity.HasCollection(p => p.Products)
               .DeleteMissingEntities();
       });  

:
, . Code- , .

+3

Source: https://habr.com/ru/post/1656922/


All Articles