You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
2.4 KiB
69 lines
2.4 KiB
using Infrastructure.Data;
|
|
using Infrastructure.Domain;
|
|
using Infrastructure.Extensions;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace Infrastructure.Web.Mvc
|
|
{
|
|
public class TreeCrudController<TEntity, TEditModel> : CrudController<TEntity, TEditModel> where TEntity : BaseTreeEntity<TEntity>
|
|
{
|
|
public TreeCrudController(IRepository<TEntity> repo) : base(repo)
|
|
{
|
|
}
|
|
|
|
public override void ToEntity(TEditModel model, TEntity entity)
|
|
{
|
|
if (entity != null && !entity.ParentId.HasValue)
|
|
{
|
|
var root = this.Repo.ReadOnlyTable().FirstOrDefault(o => o.ParentId == null);
|
|
if (root == null)
|
|
{
|
|
throw new Exception("根节点没有初始化");
|
|
}
|
|
entity.ParentId = root.Id;
|
|
}
|
|
}
|
|
|
|
protected override void BeforeEdit(TEntity entity, TEditModel model)
|
|
{
|
|
if (entity.ParentId != null)
|
|
{
|
|
if (entity.ParentId == entity.Id)
|
|
{
|
|
throw new Exception("上级节点不能是当前节点");
|
|
}
|
|
var parentNode = this.Repo.ReadOnlyTable().Where(o => o.Id == entity.ParentId).FirstOrDefault();
|
|
var parentList = this.Repo.ReadOnlyTable()
|
|
.Where(o => o.Left <= parentNode.Left && o.Right >= parentNode.Right)
|
|
.ToList()
|
|
.ToTree()
|
|
.FirstOrDefault(o => o.Id == entity.ParentId);
|
|
while (parentList is not null && parentList.ParentId.HasValue)
|
|
{
|
|
if (parentList.ParentId == entity.Id)
|
|
{
|
|
throw new Exception("上级节点不能是当前节点的下级节点");
|
|
}
|
|
else
|
|
{
|
|
parentList = parentList.Parent;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
protected override void AfterEdit(TEntity entity, TEditModel model)
|
|
{
|
|
var root = this.Repo.Table().ToList().FirstOrDefault(o => o.ParentId == null);
|
|
root.Update();
|
|
this.Repo.SaveChanges();
|
|
}
|
|
|
|
protected override void AfterDelete(List<Guid> list)
|
|
{
|
|
this.AfterEdit(default(TEntity), default(TEditModel));
|
|
}
|
|
}
|
|
} |