我有以下兩類:SQLite的EF6梯級上的許多刪除對許多
[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>();
}
}
和
[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>();
}
}
正如你所看到的,一個產品可以有多個進程,一個進程可以綁定到多種產品。 (如產品主席包括以下過程:切割,鑽孔,擰,等...
在我OnModelCreating
方法在我DataContext
我指定了多對多的關係如下:
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");
});
它創建了一個名爲ProcessProducts
新表,其中多對多的關係被存儲。
現在我的問題是,當我刪除例如從我的數據庫產品中,我想自動刪除ProcessProducts
表中的所有行,其中使用了特定的ProductId
。我想在我的模型構建器下配置CascadeDelete
,但它不允許我這樣做。
也許這是我的方式,我如何刪除該項目是錯誤的?
public void Delete(TEntity entity)
{
if (entity == null) throw new ArgumentNullException("entity");
_context.Set<TEntity>().Attach(entity);
_context.Set<TEntity>().Remove(entity);
_context.SaveChanges();
}
任何有關此事的幫助將不勝感激。