实体框架6:删除子项

时间:2014-07-30 20:36:36

标签: c# entity-framework

当我想要删除子项目时,我遇到了一个奇怪的问题:

我的模特:

public class Blog
{
    public Blog() {}

    [Key]
    [Column(Order=0)]
    public int Id { get; set; }
    public string name { get; set; }
    public BlogDetail BlogDetail { get; set; }
    public List<Post> Posts { get; set; }
}

public class BlogDetail
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Post
{
    public int Id { get; set; }
    public string Name {get ; set;}
    public int BlogId { get; set; }
}

public class BlogContext : DbContext
{
    public BlogContext() : base("BlogContextDb") { }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<BlogDetail> BlogDetail { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

public class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer<BlogContext>(new BlogInitializer());

        using (var context = new BlogContext())
        {
            context.Database.Initialize(true);

            context.Blogs.Add(new Blog()
            {
                name = "My First blog",
                BlogDetail = new BlogDetail() { Name = "Test" },

                Posts = new List<Post> { new Post { Name = "Post1" }, new Post { Name = "Post2" } }

            });

            context.Blogs.Add(new Blog
            {
                name = "Test3"
            });

            context.SaveChanges();

            Blog blog = context.Blogs.Include(f => f.BlogDetail)
                .Where(d => d.name.Equals("Mon premier blog")).SingleOrDefault();

            ((BlogDetail)blog.BlogDetail).Name = "Test1";

            context.SaveChanges();

            // try to delete the blog.
            context.Entry(blog.BlogDetail).State = EntityState.Deleted;

            // Doesn't work : throw : 
            // Additional information: Collection was modified; enumeration operation may not execute.
            blog.Posts.ForEach(c => context.Entry(c).State = EntityState.Deleted);

            // Doesn't work : throw 
            //The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. 
            //When a change is made to a relationship, the related foreign-key property is set to a null value. 
            //If the foreign-key does not support null values, a new relationship must be defined, the 
            //foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
            context.Entry(blog).State = EntityState.Deleted;
            context.SaveChanges();

    }
}

我没有找到一个干净的解决方案来删除我的帖子!

1 个答案:

答案 0 :(得分:0)

尝试

context.BlogDetail.Remove(blog.BlogDetail)
context.SaveChanges()

这就是我认为你应该删除子对象的方式

相关问题