consigo este error:EF - Eliminar en cascada que no trabaja, no se puede eliminar objetos
System.Data.SqlClient.SqlException The DELETE statement conflicted with the REFERENCE constraint "FK_comments_postId__164452B1". The conflict occurred in database "awe", table "dbo.comments", column 'postId'. The statement has been terminated.
tengo esta estructura:
public class Post
{
public long Id { get; set; }
public string Body { get; set; }
public long? ParentId { get; set; }
public virtual Post Parent { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public long Id { get; set; }
public long PostId { get; set; }
public virtual Post Post { get; set; }
public string Body { get; set; }
}
mi método de eliminación:
public void Delete(long id)
{
var p = context.Set<Post>().Get(id);
if(p == null) throw new MyEx("this post doesn't exist");
if (p.Posts.Count > 0) throw new MyEx("this post has children and it cannot be deleted");
context.Set<Post>().Remove(p);
context.SaveChanges();
}
mi DbContext:
public class Db : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}