如何从实体框架ICollection中清除()所有元素? [英] How to Clear() all elements from Entity Framework ICollection?

查看:128
本文介绍了如何从实体框架ICollection中清除()所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Clear()从实体框架的集合中删除所有元素时遇到问题

I have problems removing all elements from a collection in entity framework using Clear()

考虑博客和帖子中经常使用的示例.

Consider the often used example with Blogs and Posts.

public class Blog
{
    public int Id {get; set;}
    public string Name {get; set;}
    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int Id { get; set; }

    // foreign key to Blog:
    public int BlogId { get; set; } 
    public virtual Blog Blog { get; set; }

    public string Title { get; set; }
    public string Text { get; set; }
}

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs {get; set;}
    public DbSet<Post> Posts {get; set;}
}

一个博客有很多帖子.博客具有帖子的ICollection.博客和帖子之间存在直接的一对多关系.

A Blog has many Posts. A Blog has an ICollection of Posts. There is a straightforward one-to-many relation between Blogs and Posts.

假设我要从博客中删除所有帖子

Suppose I want to remove all Posts from a Blog

我当然可以执行以下操作:

Of course I could do the following:

Blog myBlog = ...
var postsToRemove = dbContext.Posts.Where(post => post.BlogId == myBlog.Id);
dbContext.RemoveRange(postsToRemove);
dbContext.SaveChanges();

但是,以下内容似乎更容易:

However, the following seems easier:

Blog myBlog = ...
myBlog.Posts.Clear();
dbContext.SaveChanges();

但是这会导致InvalidOperationException:

However this leads to an InvalidOperationException:

操作失败:由于一个或多个外键属性不可为空,因此无法更改该关系.对关系进行更改时,相关的外键属性将设置为空值.如果外键不支持空值,则必须定义新的关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象.

清除收藏夹的正确方法是什么?是否有流利的API语句?

What is the proper way to clear the collection? Is there a fluent API statement for this?

推荐答案

两个代码示例之间存在差异.

There is a difference between your two code samples.

您的第一个代码示例dbContext.RemoveRange(postsToRemove)将删除Post记录.因此,涉及这些记录的任何关系也将被删除.

Your first code sample dbContext.RemoveRange(postsToRemove) removes the Post records. Therefor, any relationship involving these records are also removed.

在第二个代码示例myBlog.Posts.Clear()中,您将删除myBlog及其对应的Post记录之间的关系. 实际"基础操作是将Post记录的BlogId的值设置为null.不幸的是,这是不可能的,因为BlogId设置为不可为空.因此,简而言之,该关系已删除,并且实际上没有任何记录被删除.

In your second code sample myBlog.Posts.Clear() you are removing the relationship between myBlog and its corresponding Post records. The 'real' underlying action is to set the value of BlogId of the Post records to null. Unfortunately this is not possible, since BlogId is set to not-nullable. So, in short, the relationship is removed, and no records are actually deleted.

这篇关于如何从实体框架ICollection中清除()所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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