实体框架代码首先使用级联删除
如何设置域和 LINQ 语句以便从数据库中删除记录?
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; }
}
我想做的是删除类别并能够将删除级联到所有子产品。
- 我的域中还需要任何其他附加属性吗?
- 不进行往返删除对象的 LINQ 语句是什么? (我不想选择,直接删除)。
这是唯一的方法吗?
Category category = new Category() { CategoryId = 1 } ;
context.AttachTo("Category", category);
context.DeleteObject(category);
context.Savechanges();
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.
- Is there any other additional attributes needed in my domain?
- What is the LINQ statement to delete objects without doing a round trip? (I do not want to select, just a direct delete).
Is this the only way to do this?
Category category = new Category() { CategoryId = 1 } ;
context.AttachTo("Category", category);
context.DeleteObject(category);
context.Savechanges();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您首先提到了 EF 代码,这意味着 EF 4.1,但您已经展示了在 EF 4 中删除对象的示例。在 EF 4.1 中删除对象而不从数据库加载对象的正确方法是:
如果您没有更改默认约定配置中的任何内容,它将同时删除所有相关产品,因为
OneToManyCascadeDeleteConventions
确保所有一对多关系都是使用ON CASCADE DELETE
创建的。不会有额外的数据库往返 - 对于Id
= 1 的Category
只有单个DELETE
语句。如果您愿意,可能会发生不同的情况删除完全加载的
Category
(带有加载的Products
导航属性),在这种情况下,EF 将为每个Product
创建单独的删除语句,因此您将拥有 N+数据库往返 1 次,其中 N 是类别中的产品数量。 这里是级联的方式删除 EF 中的作品。它与实体设计器相关,但描述的原理是相同的。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:
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 withON CASCADE DELETE
. There will be no additional roundtrips to database - only singleDELETE
statement forCategory
withId
= 1.The different situation can occure if you want to delete fully loaded
Category
(with loadedProducts
navigation property) in such case EF will create separate delete statement for eachProduct
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.取自VS2010自动生成的代码:
Taken from the VS2010 auto generated code: