我需要一种方法来删除用户及其在其他表中的所有约束。我知道 sql server 中的级联删除,但由于某些原因我不能使用它。
假设一个用户有几个订单,每个订单都有一些产品。所以我在方法中发送用户,它会找到订单,在 foreach 循环中它进入该订单等等。
所以我准备写一个方法来递归地做到这一点;它必须接收一个对象并找到它的所有关系并遍历它。
我首先使用 EF 电动工具逆向工程代码从数据库生成这些。这是我的课:
public partial class myDbContext: DbContext
{
...
public DbSet<Users> Users{ get; set; }
public DbSet<Orders> Orders{ get; set; }
public DbSet<Products> Products{ get; set; }
public DbSet<OrderProducts> OrderProducts{ get; set; }
...
}
public partial class Users
{
public int UserID { get; set; }
public string Username { get; set; }
public virtual ICollection<Orders> Orders{ get; set; }
}
public partial class Orders
{
public int OrderID { get; set; }
public virtual Users users { get; set; }
public virtual ICollection<OrderProducts> OPs { get; set; }
}
public partial class OrderProducts
{
public int OPID { get; set; }
public virtual Orders orders { get; set; }
public virtual Product products { get; set; }
}
使用这种方法,我能够找到virtual ICollection
用户对象中的所有 s。
private void DeleteObjectAndChildren(object parent)
{
using (var ctx = new myDbContext())
{
Type t = parent.GetType();
//these are all virtual properties of parent
var properties = parent.GetType().GetProperties().Where(p => p.GetGetMethod().IsVirtual);
foreach (var p in properties)
{
var collectionType = p.PropertyType.GetGenericArguments();
//collectionType[0] gives me the T type in ICollection<T>
//what to do next?
}
}
}
使用collectionType[0]
我看到它是Orders
,我必须有这样的东西才能查询:
var childType = ctx.Set<collectionType[0]>;
但我无法获得正确的演员阵容。
如果这是完全错误的,任何提示都会让我找到正确的方向。