我有以下两类: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();
}
任何有关此事的帮助将不胜感激。