Abp 级联查询和级联删除

Abp级联查询,主要要设置主子表的外键关系。

    [Table("School")]
    public class School : Entity<int>
    {

        public string Name { get; set; }

        public virtual List<Student> Students { get; set; } 
    }

    [Table("Student")]
    public class Student : Entity<int>
    {
        [Required]
        public virtual School School { get; set; }

        public string Name { get; set; }
    }

例如School和Student实体。在子表Student的School属性上添加[Required]标识。这样我们生成的Migration文件,就会自动生成外键和级联删除的关系。

 

 这种要注意,软删除时,不会触发级联删除。所以我们的Model不要继承ISoftDelete接口。

查询时,要注意使用GetAllIncluding方法。

 public List<School> GetAllSchool()
        {
           return _schoolRepository.GetAllIncluding(s=>s.Students).ToList();
        }

但是abp只提供了GetAll时的GetAllIncluding方法,通过Id查询单个对象时,没有。我们可以在仓储的实现中自己实现。

    public class SchoolRepository : PHMESRepositoryBase<School>, ISchoolRepository
    {
        IDbContextProvider<PHMESDbContext> _dbContext;
        public SchoolRepository(IDbContextProvider<PHMESDbContext> dbContextProvider) : base(dbContextProvider)
        {
            _dbContext = dbContextProvider;
      
        }
 
        public List<School> GetAllSchool()
        {
           var list= _dbContext.GetDbContext().school.Include(p=>p.Students).ToList();

            return list;
        }

        public School GetSchool(int id)
        {
           return _dbContext.GetDbContext().school.Where(p => p.Id == id).Include(p=>p.Students).First() ;
        }
    }

级联删除,就直接通过Id删除主表,子表也会自动删除。

        public void DeleteSchool(int id)
        {
            var a = _schoolRepository.Get(id);
            _schoolRepository.Delete(a);
        }

 

posted @ 2020-07-08 15:16  liuyong111  阅读(1278)  评论(0编辑  收藏  举报