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);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM