【问题标题】:Entity Framework composite key delete with one primary key使用一个主键删除实体框架复合键
【发布时间】:2017-04-12 12:39:03
【问题描述】:

这是我在作业中的一些数据库设计

Customer
--------
CustomerID (PK)

Cake
-------
CakeID (PK)

Cart
-------
CustomerID (PK, FK)
CakeID (PK, FK)

我想在我的 Cart Repository 类中创建一个函数 clearUserCart(User user),但我不知道如何创建函数来删除指定用户的所有行。

编辑: 我已经想出了如何做到这一点,只需使用返回List<Cart>getCartOfUser(User user)。然后做foreach循环删除。 在SQL中,只要一行DELETE FROM Cart WHERE CustomerID = <the cust id>就可以实现,实体框架中有没有等价的一行语句?

【问题讨论】:

  • 我认为阅读this会对你有所帮助

标签: c# entity-framework-6 repository-pattern


【解决方案1】:

如果您使用的是 EF 6,则可以使用 RemoveRange 方法。

所以它可能看起来像这样;

context.Cart.RemoveRange(cartItem => cartItem.CustomerID == CustomerToDelete);

【讨论】:

    【解决方案2】:

    1) 你可以使用context.Carts.RemoveRange(queryable.Where(c => c.CustomerID == <the cust id>)).
    2) 您可以添加对Entity Framework Extended Library 的引用,并使用这种语法context.Carts.Where(c => c.CustomerID == <the cust id>).Delete()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      相关资源
      最近更新 更多