Skip to content

Instantly share code, notes, and snippets.

@mota57
Last active November 26, 2018 20:57
Show Gist options
  • Save mota57/47f0f42713c5e1de5bad6dda5c876ffe to your computer and use it in GitHub Desktop.
Save mota57/47f0f42713c5e1de5bad6dda5c876ffe to your computer and use it in GitHub Desktop.
example of entity framework deleting recursively self reference table comment/review
public class Entity
{
public Guid Id { get; set; }
public string Name { get; set; }
public DateTime? CreateDate { get; set; }
public DateTime? LastUpdate { get; set; }
public bool IsActive { get; set; }
public bool Deleted { get; set; }
}
public class Review : Entity
{
public Guid UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser User { get; set; }
public Guid ArticleId { get; set; }
[ForeignKey("ArticleId")]
public Article Article { get; set; }
public Guid? ParentId { get; set; }
public Review Parent { get; set; }
public virtual ICollection<Review> Childs { get; set; }
public string Content { get; set; }
public DateTime? LastViewed { get; set; }
public Guid? ReviewBy { get; set; }
}
public class ReviewController : Controller
{
ReviewRepository repository {get; set;}
public ReviewController(ReviewRepository repo)
{
repository = repo;
}
public ActionResult Index()
{
repository.GetAll();
return View();
}
[HttpPost]
public ActionResult Delete(Guid userID)
{
repository.DeleteAllReviewsByUserId(userId);
return View();
}
}
public class ReviewRepository
{
public ApplicationDbContext DbContext {get; set;}
public ReviewRepository(ApplicationDbContext dbContext)
{
DbContext = dbContext;
}
public IEnumerable<Review> GetAll()
{
return DbContext.Reviews.GetAll();
}
public void DeleteAllReviewsByUserId(Guid userId)
{
var records = DbContext.Reviews
.Include(r => r.Childs)
.ToList()
.Where(r => r.UserId == userId); //MAKE SURE TO FILTER AFTER QUERY ALL RECORDS IN DB!!!!!
foreach (var item in records)
{
NavigateReviewToDelete(item);
}
DetachFromParent();
dbSet.RemoveRange(records);
TrackerDeletedReviews.Clear();
}
private void DetachFromParent()
{
foreach (var item in TrackerDeletedReviews)
{
item.ParentId = null;
item.Parent = null;
}
}
private void NavigateReviewToDelete(Review review)
{
AddReviewToDelete(review);
if(review.Childs != null && review.Childs.Any())
{
foreach(var item in review.Childs)
{
NavigateReviewToDelete(item);
}
}
}
private List<Review> TrackerDeletedReviews = new List<Review>();
private void AddReviewToDelete(Review review)
{
if (!TrackerDeletedReviews.Any(_ => _.Id == review.Id))
{
TrackerDeletedReviews.Add(review);
}
}
}
@mota57
Copy link
Author

mota57 commented Nov 26, 2018

line 22 of the file ReviewRepository is very important to notice the differences! The second picutre doesn't bring all childs when attempt to apply a filter.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment