Reputation: 2711
I have the following two classes:
[Table("Products")]
public class Product
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public virtual ICollection<Process> Processes { get; set; }
public Product()
{
this.Processes = new HashSet<Process>();
}
}
and
[Table("Processes")]
public class Process
{
public int Id { get; set; }
public string Name { get; set; }
public string MachineName { get; set; }
//list of all products
public virtual ICollection<Product> Products { get; set; }
public Process()
{
this.Products = new HashSet<Product>();
}
}
As you can see, One product can have multiple processes and one process can be bound to multiple products. (e.g. product Chair consists of the following processes: Cutting, Drilling, Screwing, etc...
Under my OnModelCreating
method in my DataContext
I have specified Many to Many relationships as follows:
modelBuilder.Entity<Process>()
.HasMany<Product>(s => s.Products)
.WithMany(c => c.Processes)
.Map(cs =>
{
cs.MapLeftKey("Process_ProcessId");
cs.MapRightKey("Product_ProductId");
cs.ToTable("ProcessProducts");
});
Which creates a new table named ProcessProducts
where many to many relationships are being stored.
My Problem now is, that when I remove e.g. Product from my database, I would like to automatically remove all rows from ProcessProducts
table, where the particular ProductId
has been used. I wanted to configure CascadeDelete
under my modelBuilder, but it does not allow me to do so.
Maybe it's the way, how I am removing the item which is wrong?
public void Delete(TEntity entity)
{
if (entity == null) throw new ArgumentNullException("entity");
_context.Set<TEntity>().Attach(entity);
_context.Set<TEntity>().Remove(entity);
_context.SaveChanges();
}
Any help in regards to this matter would be highly appreciated.
Upvotes: 0
Views: 312
Reputation: 3794
Do delete in cascade mode you can use SQL or EF.
Each case need to be configured how deep the cascade will go. So the question is: How deep you want to go:
If you delete a Product
should delete de Process(es)
connected with it and if this Process(es)
has other Product(s)
should cascade keep this chain of deletion?
Perhaps by cascade delete, you only meant delete the connection (many-to-many relationship) between Product
and Process
. If this is the case you only need to do:
public void DeleteProduct(Product entity)
{
if (entity == null) throw new ArgumentNullException("entity");
entity = _context.Set<Product>().First(f => f.Id == entity.Id);
_context.Set<Product>().Remove(entity);
_context.SaveChanges();
}
This should delete your Product
and all ProcessProducts
registries connected with your Product
.
Upvotes: 1