【发布时间】:2018-01-13 02:35:51
【问题描述】:
我需要一种方法来删除用户及其在其他表中的所有约束。我知道 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 ICollections。
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]>;
但我无法获得正确的演员阵容。
如果这是完全错误的,任何提示都会让我找到正确的方向。
【问题讨论】:
标签: c# sql-server generics recursion ef-power-tools