如何从多对多表中删除行

时间:2012-09-10 02:06:12

标签: c# asp.net-mvc entity-framework

作为一个例子,我可以在这3个表中列出示例字段:

作者 - > AuthorId,Name,[...]

预订 - > BookId,Title,[...]

作者书 - > AuthorId,BookId

如何从多对多表(AuthorBooks)中删除行?我想做这样的事情:

var author = db.AUTHORS.Single(x => x.AUTHORID == 1);
var fictionBooks = author.BOOKS.Where(x => x.type == "fiction");
fictionBooks.Delete(); // This is what I want to do

如何在多对多表上执行这样的删除?

1 个答案:

答案 0 :(得分:1)

您必须遍历集合并删除每个项目。您可以始终将其包装在扩展方法中,以简化删除集合,如示例中所示。

public static class FictionBookExtensions
{
    public static void Delete(IEnumerable<YourFictionBookClass> fictionBooks)
    {
        foreach (var fictionBook in fictionBooks)
        {
            db.DeleteObject(fictionBook);
        }
    }
}