实体框架代码首先用级联删除 [英] Entity framework code first delete with cascade

查看:120
本文介绍了实体框架代码首先用级联删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置我的域和LINQ语句,以便我可以从数据库中删除记录?

How do I set up my domain and the LINQ statement so I can delete a record from a database?

public class Category    {
    public int CategoryId { get; set; }
    public string Name { get; set; }

    public List<Product> Products{ get; set; }

}
public class Product {
    public int ProductId { get; set; }
    public string Name { get; set; }

    public int CategoryId {get; set; }
    public Category Category{ get; set; }
}

我想做的是删除类别并能够级联删除所有的子产品。

What I'd like to do is delete Category and be able to cascade the delete to all the child products.


  1. 我的域中是否还有其他附加属性?

  2. 什么是LINQ语句来删除对象而不做往返? (我不想选择,只是直接删除)。

这是唯一的方法吗?

Is this the only way to do this?

Category category = new Category() {  CategoryId = 1   } ; 
context.AttachTo("Category", category);
context.DeleteObject(category);
context.Savechanges();


推荐答案

你提到EF代码,这意味着EF 4.1,但你已经显示了在EF 4中删除对象的示例。在EF 4.1中删除对象的正确方法,而不从数据库加载它是:

You mentioned EF code first which means EF 4.1 but you have shown example of deleting object in EF 4. Correct approach to delete object in EF 4.1 without loading it from database is:

var category = new Category() { CategoryId = 1 };
context.Categories.Attach(category);
context.Categories.Remove(category);
context.SaveChanges();

如果您在配置defalut约定时没有更改任何内容,它也将删除所有相关产品,因为 OneToManyCascadeDeleteConventions 确保使用 ON CASCADE DELETE 创建所有一对多关系。对于类别 Id 的唯一 DELETE 语句不会有额外的往返数据库/ code> = 1。

If you didn't change anything in configuration of defalut conventions it will also delete all related products because OneToManyCascadeDeleteConventions ensures that all one-to-many relations are created with ON CASCADE DELETE. There will be no additional roundtrips to database - only single DELETE statement for Category with Id = 1.

如果要删除完全加载的类别 (加载产品导航属性)在这种情况下,EF将为每个产品创建单独的删除语句,以便您将有N +1到数据库的往返数据库,其中N是类别中的产品数量。 这里是如何级联删除在EF中工作。它与实体设计师有关,但描述的原则是相同的。

The different situation can occure if you want to delete fully loaded Category (with loaded Products navigation property) in such case EF will create separate delete statement for each Product so you will have N+1 roundtrips to database where N is number of products in category. Here is how cascade delete works in EF. It is related to entity designer but described principles are the same.

这篇关于实体框架代码首先用级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆